ruby - Need to sort array based on another array of array -


i have 2 arrays compared , sorted based on array. here follows:

a = [["a", 1075000], ["c", 1750000], ["d", 0], ["e", 0], ["b", 0]] b = ['a','b','c','d','e'] 

the array a should sorted in order follows(in compared b):

[["a", 1075000], ["b", 0], ["c", 1750000], ["d", 0], ["e", 0]] 

i have tried this:

sort_by a.sort! {|a1,b1| a1[0] <=> b1[0]} 

i assume want sort elements in a according position in b , elements in b strings 'a', 'b', etc , not constants.

then this:

a = [["a", 1075000], ["c", 1750000], ["d", 0], ["e", 0], ["b", 0]] b = ['a','b','c','d','e']  a.sort { |x, y| b.index(x.first) <=> b.index(y.first) } #=> [["a", 1075000], ["b", 0], ["c", 1750000], ["d", 0], ["e", 0]] 

depending on size of b might make sense use sort_by instead of sort. sort_by catches return value of block , not evaluate block multiple times:

a.sort_by { |x| b.index(x) } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -