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]


count += 1



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:


This uses the in-built Array#value_at method.