From Ruby Koans about_hashes.rb
:
Why might you want to use #fetch
instead of #[]
when accessing hash keys?
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.
#[]
when the key does not exist will call #default_proc
if any or else return #default
. By default, #default
returns nil
.
May 15, 2013 at 18:04
key
in the last example may not be the best name for what is yielded to the block. In the case key_name
is found, fetch will yield the value
at key_name
and the key
if not.
Nov 3, 2016 at 18:21
arr = [1,2,3]
arr[1..-2] #=> [1,2]
But not this: arr.fetch(1..-2) #=> TypeError: no implicit conversion of Range into Integer
Similarly you can mutate an array with Hash#[]
arr[1] = "A"
arr #=> ["A",2,3]
But not with fetch: arr.fetch(1) = "A" #=> unexpected '=', expecting end-of-input
With []
, the creator of the hash controls what happens when a key does not exist, with fetch
you do.
fetch
by default raises an error if the key is not found. You can supply a default value instead.
h = {}
h.fetch(:foo) # no default value, raises error
# => # ~> -:3:in `fetch': key not found: :foo (KeyError)
h.fetch(:bar, 10) # default value, returns default value
# => 10
begin h.fetch(:foo); rescue KeyError; if h.default_proc then h.default_proc.() else h.default end end
.
May 15, 2013 at 16:16