rept rept - 1 month ago 13
Ruby Question

Sort array a by value in array b in Ruby

I have an array

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g']


and another array:

b = [0, 3, 6, 3, 4, 0, 1]


Is it possible to sort array a according to values in array b?

The result should be:

a = ['c', 'e', 'b', 'd', 'g', 'a', 'f']


Something like this doesn't seem to exist in Ruby/Rails:

a.sort_with_index{ |elem, index| b[index] }


Edit: in response to the duplicate marking: the question being referred to has an array with elements having an ID, and the other array references the ID's directly. This is not the same, and the same solution will not apply...

Answer Source

You can just combine the two, sort, and strip out the original a values:

a.zip(b).sort_by { |_a, _b| -_b }.map { |_a,_| _a }