Unscramble a string given array

Write a method that takes in a string and an array of indices in the

string. Produce a new string, which contains letters from the input

string in the order specified by the indices of the array of indices.

This is how I solved it.

def scramble_string(string, positions)
letters = string.split(//)

unscrambled_arr = Array.new

count = 0
while count < positions.length
num = positions[count]

unscrambled_arr.push(letters[num])

count += 1

end

unscrambled_arr.join
end

I figure there must be a simpler way to solve it. I’m guessing it can be
done with a regular expression. Looking for a seasoned ruby programmer
to show me how they would do it.

Not tested, but something along this:

positions.map {|pos| string[pos]}.join

You create a new array, corresponding to the positions array, where each
array element is the letter from the string at the respective position.
This array of letter is then joined as in your original solution.

Another, albeit possibly slightly less efficient method (as it creates
one more intermediate array), would be:

string.chars.values_at(*positions).join

This uses the in-built Array#value_at method.

http://ruby-doc.org/core-2.2.0/Array.html#method-i-values_at

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs