mardi 26 septembre 2017

Sort array a by value in array b in Ruby [duplicate]

This question already has an answer here:

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] }

Aucun commentaire:

Enregistrer un commentaire