On Feb 2, 2008 8:02 PM, SpringFlowers AutumnMoon
<summercoolness / gmail.com> wrote:
> 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 right.  Basically, #sort gives you, on each iteration, two
elements out of your list based on it's own sort algorithm (I think it
uses a quicksort version?).  Your code can do whatever it wants to
with these elements, as long as your block returns a -1, 0, or 1 each
time.  For example, your sort may be based on a suffix instead of a
beginning character or number (i.e. hexagon vs pentagram when the
order I want is n-grams to come before n-gons).  Thus, you can define
the characteristics that must be sorted by, and those characteristics
can be sophisticated if you need them to be.

Todd