Hashes

Goals

Step 1

Type this in irb:

states = {"CA" => "California", "DE" => "Delaware"}

Arrays are ideal when we want to store an ordered list of items. We can access elements in an array by their position, but sometimes the position doesn't really help us much. We may want to access items in the list based on a name, or key. A hash stores pairs of items, associating keys with values.

The { character is typically called a 'curly brace', and the => is called a 'rocket' or 'hashrocket'

Type this in irb:

states.keys
states.values

You can ask a hash for an array of just its keys or its values.

Type this in irb:

states['CA']
states['DE']

With arrays, we accessed elements by their index, a number. With a hash, we access elements by their key.