Chris said:
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?
Sorting arrays is a complex topic that has been given a lot of attention
in computer programming. The goal is to sort the array with the fewest
comparisons, i.e. to sort it as fast as possible. You can google the
topic and read about different sorting methods--you might start by
searching 'bubble sort'.
The sort method uses an "algorithm" (or methodology) to sort the array.
In order to sort an array you have to compare the elements in the array.
The fewer times you have to compare the elements to arrive at a sorted
array the better. When ruby needs to compare two elements in the
process of sorting an array, ruby assigns the two elements to the
variables x and y. Your block then decides which of the two elements
should come first in the array. Ruby takes that result and proceeds
with the process of sorting the array.
It should be obvious to you that your block has to be called more than
once in order for ruby to sort your array--you can't sort a 5 element
array by doing one comparison of two of the elements. But what is the
minimum number of comparisons ruby needs to make in order to sort your
array?