Creating and accessing hashes

Free preview 2 min to read

A hash pairs keys with values

Arrays store values by position, like fruits[0] for the first one. A hash stores each value under a name, a key, and looks it up by that name.

user = { name: "Ada", role: "admin", active: true }

{...} is the hash literal. Each entry is a key and a value joined by a colon: name: "Ada" pairs the key :name with "Ada". This shorthand works only for symbol keys, from Ruby symbols vs strings, written without the leading colon.

The older syntax: any key type

user = { "name" => "Ada", 1 => "one", :active => true }

The => ("hash rocket") syntax accepts any object as a key: a string, a number, even another hash. Rails code uses the symbol shorthand almost everywhere. The rocket shows up when a key isn't a symbol, or in code older than Ruby 1.9, which introduced the shorthand.

Reading a value by its key

user = { name: "Ada", role: "admin" }
user[:name]     # => "Ada"
user[:role]     # => "admin"
user[:missing]  # => nil, no error, same as an array's out-of-bounds read

user[:name] looks up the value paired with :name. A key that was never set reads as nil, like fruits[10] in the arrays course.

String keys and symbol keys are different keys

This catches nearly everyone once: :name and "name" are different keys.

user = { name: "Ada" }
user[:name]     # => "Ada", the symbol key
user["name"]    # => nil, a string key was never set

It's the symbols course's distinction applied to lookups. A hash built with symbol keys answers only to symbols; a string that looks the same doesn't match.

Key takeaways

  • A hash literal pairs keys and values with : (symbol-key shorthand) or => (any key type): { name: "Ada" } or { "name" => "Ada" }.
  • hash[key] reads a value; a missing key returns nil, never an error.
  • :name and "name" are different keys and never match each other.
  • Rails code favors the symbol shorthand; the rocket appears for non-symbol keys.
Lesson 1 of 7 · free

Keep going with lesson 2

Adding, updating, and removing

Using hash[key] = value to add or update, delete to remove, and how both change the original hash.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...