RoboCode - 2 years ago 192
Ruby Question

# How to sort one array based on another array using Ruby

There are two arrays:

``````A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
B = [3, 4, 1, 5, 2, 6]
``````

I want to sort
`B`
in a way that for all the elements of
`B`
that exists in
`A`
, sort the elements in the order that is in array
`A`
.

The desired sorted resulted would be

``````B #=> [1, 2, 3, 4, 5, 6]
``````

I have tried to do

``````B = B.sort_by { |x| A.index }
``````

but it does not work.

This question differs from the possible duplicates because it deals with presence of elements in the corresponding array and no hashes are present here.

It perfectly works:

``````▶ A = [1,3,2,6,4,5,7,8,9,10]
▶ B = [3,4,1,5,2,6]
▶ B.sort_by &A.method(:index)
#⇒ [1, 3, 2, 6, 4, 5]
``````

If there could be elements in `B` that are not present in `A`, use this:

``````▶ B.sort_by { |e| A.index(e) || Float::INFINITY }
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download