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?

Community
  • 1
  • 1
rikkitikkitumbo
  • 954
  • 3
  • 17
  • 38
  • 2
    `a1.index(x.id)` returns `x`'s position in the `a1` array. `sort_by` uses that info to sort the `a2` array. – jvnill Jul 24 '14 at 01: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! – rikkitikkitumbo Jul 24 '14 at 01:55

1 Answers1

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.

ichigolas
  • 7,595
  • 27
  • 50