Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is going on in ruby's sort method?

Tags:

ruby

What do 'a' and 'b' represent in the following code, and how is the <=> working?

list = [1,2,3,4,5]
list.sort { |a,b| b <=> a }

#=> [5,4,3,2,1]
like image 602
djb Avatar asked Aug 30 '11 21:08

djb


People also ask

How do you sort hashes in Ruby?

Sorting Hashes in Ruby To sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.

How do you sort an array in ascending order in Ruby?

You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)

What does the sort method return?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.


1 Answers

The a and b represent a pair of items. It could be any two taken out of your original list. The <=> is usually called the spaceship operator. It returns 0 if the two items are equal, -1 if the one on the left is smaller, and 1 if the one on the right is smaller.

There's more info on the spaceship operator in the Ruby API docs. That's the doc for the one on Fixnum since that's what was in your example, but you can check out the definition for Float, String, etc. there as well.

Updated: The sort function expects the block it's given to follow the same behavior as the spaceship operator. If the first argument, a should be sorted first, -1 should be returned; if the second argument, b should be sorted first, 1 should be returned; and so on. So in the example of list.sort { |a,b| a + b } you're telling sort that the second argument is bigger every time, since a + b is greater than 1 for every possible combination in that list. So what you're seeing when you get [5,3,1,4,2] is basically an artifact of the order that elements are passed to the block and would likely not be stable across Ruby implementations.

like image 196
Emily Avatar answered Oct 05 '22 01:10

Emily