Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Chapter 5. Hashes

Hashes and arrays are the two basic "aggregate" data types supported by most modern programming lagnguages. The basic interface of a hash is similar to that of an array. The difference is that while an array stores items according to a numeric index, the index of a hash can be any object at all.

Arrays and strings have been built into programming languages for decades, but built-in hashes are a relatively recent development. Now that they're around, it's hard to live without them: they're at least as useful as arrays.

You can create a Hash by calling Hash.new or by using one of the special sytaxes Hash[] or {}. With the Hash[] syntax, you pass in the initial elements as comma-separated object references. With the {} syntax, you pass in the initial contents as comma-separated key-value pairs.

	empty = Hash.new                            # => {}
	empty ={}                                   # => {}
	numbers = { 'two' => 2, 'eight' => 8} # => {"two"=>2, "eight"=>8}
	numbers = Hash['two', 2, 'eight', 8]        # => {"two"=>2, "eight"=>8}

Once the hash is created, you can do hash lookups and element assignments using the same syntax you would use to view and modify array elements:

	numbers["two"]                              # => 2
	numbers["ten"] = 10                         # => 10
	numbers                                     # => {"two"=>2, "eight"=>8, "ten"=>10}

You can get an array containing the keys or values of a hash with Hash#keys or Hash#values. You can get the entire hash as an array with Hash#to_a:

 numbers.keys # => ["two", "eight", "ten"] numbers.values # => [2, 8, 10] numbers.to_a # => [["two", 2], ["eight", 8], ["ten", ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required