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]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
aandbrepresent 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
sortfunction expects the block it’s given to follow the same behavior as the spaceship operator. If the first argument,ashould be sorted first, -1 should be returned; if the second argument,bshould be sorted first, 1 should be returned; and so on. So in the example oflist.sort { |a,b| a + b }you’re telling sort that the second argument is bigger every time, sincea + bis 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.