← Back to Ruby Course | Chapter 5: Hashes | Lesson 2 of 7

Accessing Values

You get a value from a hash by asking for its key with square brackets, like looking up a word in a dictionary. If the key is not there, Ruby gives back nil.

In this page:

  1. Accessing Values
Syntax
ruby
hash[key]
hash.fetch(key)
hash.fetch(key, default_value)
hash[key] = new_value

Accessing Values

A hash value is read with square brackets, hash[key], which returns nil if the key doesn't exist rather than raising an error.

.fetch(key) is a stricter alternative that raises a KeyError for a missing key, or accepts a default as a second argument. Choosing between [] and .fetch depends on whether a missing key should be treated as an error.

Note: Use .fetch(key) instead of [] when a missing key should be treated as a bug, not silently return nil.

Example: Accessing Values

markup
person = { name: "Alice", age: 30 }

puts person[:name]
puts person[:missing_key].inspect

puts person.fetch(:age)
puts person.fetch(:missing_key, "default value")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading person[:missing_key] and using the result as if it exists, when it returns nil and can cause NoMethodError later.
  2. Using fetch without a default for a missing key, which raises KeyError.
  3. Using a string key on a symbol-key hash, such as person["name"], which returns nil.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.