Download this source
# Arrays can be done anonymously
a = [1,2,3,4]
b = ["one",2,"3",4]
puts a
b.each { | it |
puts it
}
# or not. They size dynamically.
a = Array.new
a[0] = "this"
a[1] = "is"
a[2] = "my"
a[3] = "message"
puts a
# incidentally, yet another alternative to anonymous arrays for the above is
a = %w{ this is my message }
puts a
# Hashes are similar.
h = {
"first" => "Ross",
"last" => "Bamford",
"job" => "jobless drifter"
}
puts h['first'] + " " + h['last'] + " is a " + h['job']
# By default a Hash returns nil for a non-existent key
h = Hash.new
if h['dunno'] == nil
puts "It's nil!"
else
puts "It's not! It's #{h['dunno']}"
end
# Sometimes it's more convenient to have it return something else, like zero
# if using the hash to count occurences, or whatever.
h = Hash.new("dunno mate")
h['ross'] = "Bamford"
h['rosie'] = "Randall"
puts h['ross'] # Bamford
puts h['rosie'] # Randall
puts h['john'] # dunno mate
Running this outputs:
1
2
3
4
one
2
3
4
this
is
my
message
this
is
my
message
Ross Bamford is a jobless drifter
It's nil!
Bamford
Randall
dunno mate

