Accessing Values
In this page:
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
person = { name: "Alice", age: 30 }
puts person[:name]
puts person[:missing_key].inspect
puts person.fetch(:age)
puts person.fetch(:missing_key, "default value")
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: