I am very eager to know about the Enum#sort{|a,b|..}
http://www.ruby-doc.org/core-2.0/Enumerable.html#method-i-sort
Now my question is about the internal mechanism.
***Returns an array containing the items in enum sorted, either
according to their own <=> method, or by using the results of the
supplied block. The block should return -1, 0, or +1 depending on the
comparison between a and b.**
I took the below as an example:
dogs = [
{ name: "Rover", gender: "Male" },
{ name: "Max", gender: "Male" },
{ name: "Fluffy", gender: "Female" },
{ name: "Cocoa", gender: "Female" }
]
# gender asc, name asc
p(dogs.sort do |a, b|
[a[:gender], a[:name]] <=> [b[:gender], b[:name]]
end)
#=> [{:name=>"Cocoa", :gender=>"Female"}, {:name=>"Fluffy",
:gender=>"Female"}, {:name=>"Max", :gender=>"Male"}, {:name=>"Rover",
:gender=>"Male"}]
My question is using the method `<=>` returns value `-1,0,+1`,how the
method sorting the source array ? What the things are actually going on
with the result of `<=>`?
···
--
Posted via http://www.ruby-forum.com/.