You can create an array by listing some items within
square brackets ([]) and separating them with
commas. Ruby's arrays can accomodate diverse object types.
Arrays can be concatenated or repeated just as strings can. See for yourself!
ary = [1, 2, "3"] ary + ["foo", "bar"] |
Output
ruby> ary = [1, 2, "3"] [1, 2, "3"] ruby> ary + ["foo", "bar"] [1, 2, "3", "foo", "bar"]
ary = [1, 2, "3"] ary * 2 |
Output
ruby> ary = [1, 2, "3"] [1, 2, "3"] ruby> ary * 2 [1, 2, "3", 1, 2, "3"]
We can use index numbers to refer to any part of a array. Negative indices mean offsets from the end of an array, rather than the beginning. The index of the last character is -1.
ary = [1, 2, "3"] ary[0] ary[0,2] ary[0..1] ary[-2] ary[-2,2] ary[-2..-1] |
Output
ruby> ary = [1, 2, "3"] [1, 2, "3"] 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 can be converted to and from strings, using join
and split respecitvely:
ary = [1, 2, "3"]
str = ary.join(":")
puts str.split(":") |
Output
ruby> ary = [1, 2, "3"] [1, 2, "3"] ruby> str = ary.join(":") "1:2:3" ruby> puts str.split(":") 1 2 3 nil ruby> exit
We could use join to modify the preceeding example better so that each array item is printed, separated by spaces (without using eval.rb):
ary = [1, 2, "3"]
puts "ary[0]=#{ary[0]}"
puts "ary[0,2]=#{ary[0,2].join(" ")}"
puts "ary[0..1]=#{ary[0..1].join(" ")}"
puts "ary[-2]=#{ary[-2]}"
puts "ary[-2,2]=#{ary[-2,2].join(" ")}"
puts "ary[-2..-1]=#{ary[-2..-1].join(" ")}" |
Output
ary[0]=1 ary[0,2]=1 2 ary[0..1]=1 2 ary[-2]=2 ary[-2,2]=2 3 ary[-2..-1]=2 3
Hashes
An associative array has elements that are accessed not by
sequential index numbers, but by keys which can have any sort
of value. Such an array is sometimes called a hash or
dictionary; in the ruby world, we prefer the term
hash. A hash can be constructed by quoting pairs of items
within curly braces ({}). You use a key to find
something in a hash, much as you use an index to find something in an
array.
h = {1 => 2, "2" => "4"}
h[5] = 10 # appending an entry
h.delete 1
h[1]
h |
Output
ruby> h = {1 => 2, "2" => "4"} {1=>2, "2"=>"4"} ruby> h[5] = 10 # appending an entry 10 ruby> h.delete 1 2 ruby> h[1] nil ruby> h {5=>10, "2"=>"4"} ruby> exit
Here is a similar program (that is not run through eval.rb) that you can play with to understand Ruby arrays better:
h = {1 => 2, "2" => "4"}
puts "h[1] = #{h[1]}"
puts "h[\"2\"] = #{h["2"]}"
puts "h[5] = #{h[5]}"
h[5] = 10 # appending an entry
puts "after appending an entry:"
puts "h[5] = #{h[5]}"
h.delete 1
puts "Deleted entry with key 1"
puts "h[1] = #{h[1]}"
puts "h[\"2\"] = #{h["2"]}"
puts "h[5] = #{h[5]}" |
Output
h[1] = 2 h["2"] = 4 h[5] = after appending an entry: h[5] = 10 Deleted entry with key 1 h[1] = h["2"] = 4 h[5] = 10


