Reputation: 3295
I have an array of objects and I need to sort them by the values of an attribute. The order to sort is given in the second array.
a = [ object1, object2, object3, object4]
object1.job = 'ER'
object2.job = 'AD'
object3.job = 'WE'
object4.job = 'ER'
b = ['ER', 'ER', 'WE', 'AD']
I need to sort my array a
so that it returns [object1/object4, object3, object2]
. How can I use my array b
as a key for the sorting?
Upvotes: 1
Views: 57
Reputation: 95242
This should work:
sorted_a = a.sort_by { |obj| b.index obj.job }
Note that b
doesn't need to have multiple copies of ER
; it just needs to indicate that ER
comes before WE
and AD
.
b = ['ER', 'WE', 'AD']
The index
function returns the position of its argument in its invocant:
b.index 'ER' #=> 0
b.index 'AD' #=> 2
And the sort_by
method runs the supplied block on each element of the array and uses the results as the keys to sort by.
Upvotes: 4