Gary Wright
5/9/2007 2:41:00 PM
On May 9, 2007, at 10:01 AM, Jorge Domenico Bucaran Romano wrote:
> I want a demonstrative implementation of the sort method to see how
> the
> callback (passed block) is handled, specifically the comparison result
> <=>.
Sorting is a *big* topic. Ultimately though it comes down to comparing
two elements in the array and then rearranging those elements based on
the result. As the algorithm proceeds it compares different pairs of
items until the list is completely sorted.
The common thread among all sorting algorithms is the need to decide
the order between two elements and this is the purpose of the block
provided to #sort:
[4,1,2,3].sort { |a,b| a <=> b } # => [1, 2, 3, 4]
[4,1,2,3].sort { |a,b| b <=> a } # => [4, 3, 2, 1]
So whenever sort needs to know the ordering of two objects, a and b,
its calls out to the block for the answer. If the block returns -1
then a is considered 'less than' b, 0 means they are equal, and 1
means that a is 'greater than' b. The block will be called *many*
times during the sort operations:
[4,1,2,3].sort { |a,b| puts "#{a}, #{b}"; a <=> b }
output:
4, 2
2, 3
4, 3
1, 3
2, 1
By using a block to compare the two items it allows the sorting
order to be based on whatever criteria is desired--as long as the
block returns -1, 0, or 1 the algorithm can figure the rest out.
It isn't clear if you are interested in the sorting algorithm itself,
the
mechanism by which the block is called and its result used or
something else
entirely but maybe I've provided enough information that you can
clarify your interest.
Gary Wright