February 2, 2004 Intro to Ruby Slide #10
Prev Next

Array Methods

Arrays are accessed with square brackets:
     a = [ "a", "b", "c", "d", "e" ]
     a[2] + a[0] + a[1]   =>  "cab"
     a[6]                 =>  nil
     a[1, 2]              =>  ["b", "c"]
     a[1..3]              =>  ["b", "c", "d"]
     a[4..7]              =>  ["e"]
     a[6..10]             =>  nil
     a[-3, 3]             =>  ["c", "d", "e"]

Many of the array functions we know and love in Perl are methods in Ruby's Array class:
     a.pop                =>  "e"
     a                    =>  [ "a", "b", "c", "d" ]
     a.shift              =>  "a"
     a                    =>  [ "b", "c", "d" ]
     a.push('z')          =>  [ "b", "c", "d", "z" ]
     a.map{|x| x.upcase}  =>  [ "B", "C", "D", "Z" ]

Some differences:
     a = []               =>  []
     a.empty?             =>  true
     a = %w(dog cat pony) =>  ["dog", "cat", "pony"]
     a.empty?             =>  false
     b = a.sort           =>  ["cat", "dog", "pony"]
     a                    =>  ["dog", "cat", "pony"]
     a.sort!              =>  ["cat", "dog", "pony"]
     a                    =>  ["cat", "dog", "pony"]


Prev Copyright © 2004 Walter C. Mankowski Next