



(4 ratings)
A second look at Array#sort
We have already used Array#sort to sort strings and integers. But how can we sort a more complex structure?
When the default behaviour is not what you want, Array#sort allows you to tell it how to sort the data structure. Let's start with an example simpler than the addressbook:
friends = [ |
We know that, by defalt, Array#sort will sort by the first entry - in this case, first names. But say that we want to sort by last names instead. Array#sort is not an iterator, but just like iterators it allows you to give it a block of code. Like so:
friends.sort do |a,b| |
What this code should do is:
- Return -1 if a is less than b
- Return 0 if a is equal to b
- Return 1 if a is greater than b
With this information, the sort function knows how to sort your array.
Return values
How do you "return" a value? The return value is simply the value of the last statement executed. Let's take another look at irb
>> num = 3 |
That => 3 and that => 5 are the return values of those expressions.
The <=> operator.
Sorting is so common, that there is an operator to simplyfy return values. The operator <=>irb returns the -1, 0, or 1 that you would normally have received. Try it in
>> 3 <=> 1 # 3 > 1 so <=> returns 1 |
Sorting by last name
So we have:
friends.sort do |a,b| |
a and b are elements of the array friends. The usual "friends.sort" is equivalent to:
friends.sort do |a,b| |
But we want to sort by the second entry (last name). So, instead we do:
friends = friends.sort do |a,b| |
Sorting the addressbook
Now that we understand Array#sort better, we are ready to use a customized sort of the addressbook. We have:
addressbook.sort do |person_a, person_b| |
person_a and person_b are both person structures. We can, for instance, sort them alphabetically by first name.
# p_a == "person a" |
Exercises
Write down the code to sort addressbook by full name. That is, first name, then last.
20 Random Tutorials from the same category :
Iterators In RUBY
Classes and methods in RUBY
Sorting the addressbook RUBY
Hashes In RUBY
More features IN RUBY
Implementing AddressBook In RUBY
Printing the addressbook RUBY
Difference of Gtk+ and Ruby/Gtk
Progress Bars with GD2 and Ruby
Example: Addressbook RUBY
The Scalability of Ruby
What can ruby arrays do?
Arrays In RUBY
Writing iterators In RUBY













