Prev - DUP - Next - TOC

Arrays and associative arrays


Ruby also deals with arrays. We can make an array by quoting with `[]'. Ruby's arrays are capable of containing many types of objects.

 ruby> ary = [1, 2, "3"]
 [1, 2, "3"]

Arrays can be concatenated or repeated in the same manner as strings.

 ruby> ary + ["foo", "bar"]
 [1, 2, "3", "foo", "bar"]
 ruby> ary * 2
 [1, 2, "3", 1, 2, "3"]

We can get a part of a array.

 ruby> ary[0]
 1
 ruby> ary[0,2]
 [1, 2]
 ruby> ary[0..1]
 [1, 2]
 ruby> ary[-2]
 2
 ruby> ary[-2,2]
 [2, "3"]
 ruby> ary[-2..-1]
 [2, "3"]

Arrays and Strings are convertable. An array converts into a string with `join', and a string is split into an array with `split'.

 ruby> str = ary.join(":")
 "1:2:3"
 ruby> str.split(":")
 ["1", "2", "3"]

Assosiative arrays are another important data structure. An associative array is an array with keys which can be valued in any way. Assosiative arrays are called hashes or dictionaries. In ruby world, we usually use hash. A hash is constructed by a `{ }' form.

 ruby> hash = {1 => 2, "2" => "4"}
 {1=>2, "2"=>"4"}
 ruby> hash[1]
 2
 ruby> hash["2"]
 "4"
 ruby> hash[5]
 nil
 ruby> hash[5] = 10     # appending value
 ruby> hash
 {5=>10, 1=>2, "2"=>"4"}
 ruby> hash[1] = nil    # deleting value
 nil
 ruby> hash[1]
 nil
 ruby> hash
 {5=>10, "2"=>"4"}

Thanks to arrays and hashes, we can make data containers easily.


Prev - DUP - Next - TOC