(4 ratings)   
By: math.umd.edu
This is all very nice, but can I do anything cool with arrays? You sure can. Follow this tutorial and ou will find out how.
Added: 23 June 2008    Views: 120  
PathComputers    Programming    Ruby
Keywords: computers   programming   ruby   coder   code   language   arrays  
Do you like this tutorial? Now you can support our team to add more :     
 
 
 

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 ]
=> [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 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
=> ["Melissa", "Daniel", "Jeff"]
>> names.to_s
=> "MelissaDanielJeff"
>> primes
=> [11, 5, 7, 2, 13, 3]
>> primes.to_s
=> "11572133"

Exercises

  1. 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

About the Author :
math.umd.edu
What can ruby arrays do?
Articles and Tutorials Directory by www.learnfobia.com
 Rate this tutorial : Rate 1Rate 2Rate 3Rate 4Rate 5
  |    Add to Favorites
  |    Send to Friend
  |    Print
Comments