From: Robert Dober Date: 2007-05-09T17:18:43+09:00 Subject: Re: Implementation of the object.sort method. On 5/9/07, Jorge Domenico Bucaran Romano wrote: > Hi, > > Can you show me an implementation of the Array.sort method? This > implementation would be demonstrative only. This would handle when a > block is passed. The reason is I have trouble understanding why the > following code works as expected: > > [3,2,1,4].sort do |a,b| > a <=> b > end > > I know it will sort my array but I don't understand the way this method > works because other tests I have made bring none results. > > Regards, Jorge. > Actually you do not need to know anything about the implementation. Ruby uses a modified Quicksort as Phrogz pointed out. The block is just delivering the operation *every* sorting algorithm must eventually apply, "comparison". The result of the block applied to two arbitrary elements of the array (assigned to the parameters a and b) will determine if the LHS is smaller, equal or greater than the RHS. (depending on the values <0, 0 or >0 respectively). If you use the variation #sort_by the block will be applied to both elements first and the results of these applications are compared than (using <=> if I am not mistaken ). If you understand the differnce bewteen a.sort{ rand } and a.sort_by{ rand } you have grasped the concept. HTH Robert -- You see things; and you say Why? But I dream things that never were; and I say Why not? -- George Bernard Shaw