From: Brian Candler Date: 2007-05-10T00:03:17+09:00 Subject: Re: Implementation of the object.sort method. On Wed, May 09, 2007 at 11:01:58PM +0900, 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 > <=>. > > For example, in the following code: > > puts [4,5,3,2,1].sort do |a,b| > -1 > end > > puts [4,5,3,2,1].sort do |a,b| > 1 > end > > Both print the array sorted down up. I don't understand how this is > possible It's an artefact of the quicksort algorithm. If you lie to it about how the elements compare, as you are doing above, then you'll get strange results. > so I wanted to see a demonstrative (but factual) implementation > of the sort method to see how this parameters are handled. # Noddy sort def mysort(arr, &blk) blk ||= proc { |a,b| a <=> b } # default if no block passed (0...arr.size-1).each do |i| (i+1...arr.size).each do |j| arr[i],arr[j] = arr[j],arr[i] if blk.call(arr[i],arr[j]) > 0 end end arr end p mysort([4,5,3,2,1]) { |a,b| puts "Comparing #{a} and #{b}"; a <=> b } Please don't use this as an example of a good sort algorithm! But it shows how to do callbacks. B.