jspartanx86 jspartanx86 - 7 months ago 13
Ruby Question

Select specific character positions from string

I'm looking for a way to select pseudo random characters from a string.

For example, I have a 64 character string. I would like to pick positions 0, 1, 4, 5, 8, 9.

Or a harder one would be with the same string, I would pick positions 0, 1, 2, 4, 6, 8, 10, 11, 12 and so on.

Is there a quick way to do this?

vee vee
Answer

Yes, you could use Array#values_at

> "64charstring".chars.values_at(*[0, 1, 4])
=> ["6", "4", "a"]

Update:

And if you'd like to get string result - join the result.

> "64charstring".chars.values_at(*[0, 1, 4]).join
=> "64a"