1

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

  • The order_array (an array of ids in a weird order that I want): a1 = [34, 54, 12, 43]
  • The list of objects (that I want to order): a2 = [ {id: 54, name: "greg"}, {...}, {...}, {...} ]
  • a2.sort_by{|x| a1.index x.id}

What is going on with this little piece of code?

2
  • 2
    a1.index(x.id) returns x's position in the a1 array. sort_by uses that info to sort the a2 array. Commented Jul 24, 2014 at 1:37
  • ahhh... so, a1.index(x.id) means we are assigning index values to each id kinda like [3, 5, 2, 6].index(2) would give me '2' as the answer. and then from there we are just sorting by those index values, which of course will be 0,1,2,3,4,5, etc! Commented Jul 24, 2014 at 1:55

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.