From: SpringFlowers AutumnMoon Date: 2008-02-03T11:02:25+09:00 Subject: Re: how does sort work? Chris Sepic wrote: > I'm confused as to how the sort method works. > > If I have: > a = [ "d", "a", "e", "c", "b" ] > > I know that > a.sort {|x,y| x <=> y } (or just .sort) > = ["a", "b", "c", "d", "e"] > > and > a.sort {|x,y| y <=> x } > = ["e", "d", "c", "b", "a"] > > I understand how the <=> operator works, but what exactly is going on in > the block? What are x and y assigned to? 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. -- Posted via http://www.ruby-forum.com/.