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:
Syntax
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
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
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
- Reading
person[:missing_key]and using the result as if it exists, when it returnsniland can causeNoMethodErrorlater. - Using
fetchwithout a default for a missing key, which raisesKeyError. - Using a string key on a symbol-key hash, such as
person["name"], which returnsnil.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: