Chapter 10: Hash

A Hash is similar to an Array, but stores a list of key-value pairs. In an array, each element has a positional index, but a Hash key can be anything, and the key has to be unique.

In other words,

  • An Array index is always a number.
  • A Hash key can be (almost) any object.

Most likely, a Hash key will be a symbol or a string.

There are two ways to create a Hash. The newer version can only be used when the Hash keys are symbols.

# older version
person = { :name => 'David', :framework => 'Rails' }
person = { 'name' => 'David', 'framework' => 'Rails' }

# newer version
person = { name: 'David', framework: 'Rails' }

You can access the Hash values like an Array. The only difference is that you’ve to pass the key, instead of an index.

person = { :name => 'David', :framework => 'Rails' }
person[:name]  # David
person[:framework]  # Rails


person = { 'name' => 'David', 'framework' => 'Rails' }
person['name']  # David
person['framework']  # Rails

To check if a Hash contains a key, use the include? method. It’s also aliased as has_key?, key?, and member?.

language = { name: 'Ruby', type: 'Dynamic' }

language.include? 'name'  # true
language.include? 'creator'  # false

To get all the keys and values as an Array, use the aptly named keys and values methods on the Hash.

person = { 'name' => 'David', 'framework' => 'Rails' }

person.keys  # ['name', 'framework']
person.values  # ['David', 'Rails']

In addition to these methods, there are many other useful methods you can use on the Array. For a complete reference, check out the Hash documentation.

Next: Conditions