From Ruby Koans about_hashes.rb
:
Why might you want to use #fetch
instead of #[]
when accessing hash keys?
Hash#fetch() is a Hash class method which returns a value from the hash for the given key. With no other arguments, it will raise a KeyError exception. Syntax: Hash.fetch() Parameter: Hash values. Return: value from the hash for the given key.
By default, using #[] will retrieve the hash value if it exists, and return nil if it doesn't exist *. Using #fetch gives you a few options (see the docs on #fetch): fetch(key_name) : get the value if the key exists, raise a KeyError if it doesn't.
The hashes that you've seen so far have single key/value pairs. However, just like arrays, they can be nested, or multidimensional.
In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.
By default, using #[]
will retrieve the hash value if it exists, and return nil if it doesn't exist *.
Using #fetch
gives you a few options (see the docs on #fetch):
fetch(key_name)
: get the value if the key exists, raise a KeyError
if it doesn'tfetch(key_name, default_value)
: get the value if the key exists, return default_value
otherwisefetch(key_name) { |key| "default" }
: get the value if the key exists, otherwise run the supplied block and return the value.Each one should be used as the situation requires, but #fetch
is very feature-rich and can handle many cases depending on how it's used. For that reason I tend to prefer it over accessing keys with #[]
.
* As Marc-André Lafortune said, accessing a key with #[]
will call #default_proc
if it exists, or else return #default
, which defaults to nil
. See the doc entry for ::new
for more information.
With []
, the creator of the hash controls what happens when a key does not exist, with fetch
you do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With