Hash

From RubySpec

Jump to: navigation, search

In Ruby, Hash objects are used for associative arrays(also known as maps and dictionaries). The key can be any object type.

Examples:

Hash with default value of 0:

h = {0} # or h = Hash.new(0)

Adding New Key-Value pairs:

h["Bob"] = 93   # number specific to Bob, "Bob" is the key, 93 is the value
h["Alice"] = 55

Checking whether a key is added:

h.has_key?("Bob")

Iterating through a Hash:

h.each_key {|key| puts "Key is #{key}, Value is #{h[key]}"}
Personal tools