rikkitikkitumbo
rikkitikkitumbo

Reputation: 976

Sorting an array using another array

I was looking for a way to sort an array using another array. Here was an answer that worked for me:

What is going on with this little piece of code?

Upvotes: 1

Views: 834

Answers (1)

ichigolas
ichigolas

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

Related Questions