Robert Klemme
2/3/2008 5:20:00 PM
On 03.02.2008 04:09, Chris Sepic wrote:
>> to understand this, you can think of "sort" taking a function as a
>> parameter. and sort() will pass 2 numbers to this function, and
>> rearragne the elements according to the return value of -1, 0, or 1.
>>
>> that's it. to understand it fully, you can read about "iterators" in
>> Ruby. where you can take a block as a function, and "yield" arguments
>> to this function, and get back a return value.
>
> I understand sorting and sorting algorithms - I was tripped up by the
> function as a parameter thing. Thanks!
Yeah, a block is an anonymous function.
You can see how it works if you insert a print statement:
irb(main):001:0> a = [ "d", "a", "e", "c", "b" ]
=> ["d", "a", "e", "c", "b"]
irb(main):002:0> a.sort {|x,y| p [x,y]; x<=>y}
["d", "e"]
["e", "b"]
["d", "b"]
["a", "d"]
["c", "d"]
["b", "a"]
["a", "c"]
["b", "c"]
=> ["a", "b", "c", "d", "e"]
irb(main):003:0>
A nice quiz might be to find out the sorting algorithm based on this
output. :-)
Kind regards
robert