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

Hashes

Hashes can also be initialized in a number of ways:
     h1 = {}        # empty hash
     h2 = Hash.new  # same as h1

     h3 = {"dog" => "bark", "cat" => "meow"}
     h4 = Hash["dog" => "bark", "cat" => "meow"]  # same as h3

     h5 = Hash.new(0) # set default value to 0

Hashes are accessed with square brackets, just like arrays:
     h3["dog"]   => "bark"
     h3["cat"]   => "meow"
     h3["cow"]   => nil

And hashes have lots of useful methods:
     h3.keys     => ["cat", "dog"]
     h3.values   => ["meow", "dog"]
     h3.length   => 2


Prev Copyright © 2004 Walter C. Mankowski Next