



(4 ratings)
This is all very nice, but can I do anything cool with arrays? You sure can.
Array#sort
You can sort arrays with the method Array#sort.
>> primes = [ 11, 5, 7, 2, 13, 3 ] |
Array#reverse
You can reverse arrays:
>> names |
Array#length
You can find out how long the array is:
>> names.length |
Array arithmetic
The methods Array#+, Array#-, and Array#* work the way that you would expect. There is no Array#/ (how would you divide an array?)
>> names = [ "Melissa", "Daniel", "Jeff" ] |
Naturally, their friends +=, -= and *= are still with us.
Printing arrays
Finally, you can print arrays.
>> names |
Remember that the nill means that puts returns nothing. What do you think happens if you try to convert an array to a string with Array#to_s?
>> names |
Exercises
What do you think that this will do?:
>> addresses = [ [ 285, "Ontario Dr"], [ 17, "Quebec St"], [ 39, "Main St" ] ]
>> addresses.sort
How about this?:
>> addresses = [ [ 20, "Ontario Dr"], [ 20, "Main St"] ]
>> addresses.sort
Try these out in irb
20 Random Tutorials from the same category :
More features IN RUBY
Hashes In RUBY
Example: Addressbook RUBY
Difference of Gtk+ and Ruby/Gtk
What can ruby arrays do?
Classes and methods in RUBY
Implementing AddressBook In RUBY
The Scalability of Ruby
Printing the addressbook RUBY
Iterators In RUBY
Writing iterators In RUBY
Progress Bars with GD2 and Ruby
Arrays In RUBY
Sorting the addressbook RUBY













