I am having a problem understanding how array.sort{ |x,y| block }
works exactly, hence how to use it?
An example from Ruby documentation:
When you have an array of, let's say, integers to sort, it's pretty straightforward for sort
method to order the elements properly - smaller numbers first, bigger at the end. That's when you use ordinary sort
, with no block.
But when you are sorting other objects, it may be needed to provide a way to compare (each) two of them. Let's say you have an array of objects of class Person
. You probably can't tell if object bob
is greater than object mike
(i.e. class Person
doesn't have method <=>
implemented). In that case you'd need to provide some code to explain in which order you want these objects sorted to sort
method. That's where the block form kicks in.
people.sort{|p1,p2| p1.age <=> p2.age}
people.sort{|p1,p2| p1.children.count <=> p2.children.count}
etc. In all these cases, sort
method sorts them the same way - the same algorithm is used. What is different is comparison logic.