Reputation: 976
I was looking for a way to sort an array using another array. Here was an answer that worked for me:
a1 = [34, 54, 12, 43]
a2 = [ {id: 54, name: "greg"}, {...}, {...}, {...} ]
a2.sort_by{|x| a1.index x.id}
What is going on with this little piece of code?
Upvotes: 1
Views: 834
Reputation: 7725
What happens here is that sort_by
uses the block you pass to it to map the array into sortable elements. This way the elements can be compared using the <=>
method. All comparable objects must implement this method, in this case integers.
sort
uses a sort algorithm (probably not bubble sort, taking the return value of the block as the value being sorted.
So, this expression:
a2.sort_by { |x| a1.index x.id }
... would yield the same results as running:
a2.map { |x| a1.index x.id }.sort
... where x.index(x.id)
returns the index of the current element's id property in the a1
array.
Upvotes: 2