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
.
shell> irb --simple-prompt
>> primes = [ 11, 5, 7, 2, 13, 3 ]
=> [11, 5, 7, 2, 13, 3]
>> primes.sort
=> [2, 3, 5, 7, 11, 13]
>> names = [ "Melissa", "Daniel", "Samantha", "Jeffrey"]
=> ["Melissa", "Daniel", "Samantha", "Jeffrey"]
>> names.sort
=> ["Daniel", "Jeffrey", "Melissa", "Samantha"]
Array#reverse
¶
You can reverse arrays:
>> names
=> ["Melissa", "Daniel", "Samantha", "Jeffrey"]
>> names.reverse
=> ["Jeffrey", "Samantha", "Daniel", "Melissa"]
Array#length
¶
You can find out how long the array is:
>> names.length
=> 4
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" ]
=> ["Melissa", "Daniel", "Jeff"]
>> names + [ "Joel" ]
=> ["Melissa", "Daniel", "Jeff", "Joel"]
>> names - [ "Daniel" ]
=> ["Melissa", "Jeff"]
>> names * 2
=> ["Melissa", "Daniel", "Jeff", "Melissa", "Daniel", "Jeff"]
Naturally, their friends +=
, -=
and *=
are still with us.
Printing arrays¶
Finally, you can print arrays.
>> names
=> ["Melissa", "Daniel", "Jeff"]
>> puts names
Melissa
Daniel
Jeff
=> nil
Remember that the nil 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
=> ["Melissa", "Daniel", "Jeff"]
>> names.to_s
=> "MelissaDanielJeff"
>> primes
=> [11, 5, 7, 2, 13, 3]
>> primes.to_s
=> "11572133"