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

Accessing Values

In this page:

  1. Accessing Values

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")
🔒

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.