91

From Ruby Koans about_hashes.rb:

Why might you want to use #fetch instead of #[] when accessing hash keys?

0

3 Answers 3

172

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
  • fetch(key_name, default_value): get the value if the key exists, return default_value otherwise
  • fetch(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.

4
  • 12
    Good answer, except it is not technically correct. #[] 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
  • @Marc-AndréLafortune thanks, I learnt something new! Updated answer.
    – Jon Cairns
    May 16, 2013 at 8:29
  • Point of clarification, 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.
    – Adam Grant
    Nov 3, 2016 at 18:21
  • However, you can do this: 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
    – Adzz
    May 4, 2017 at 23:30
32

With [], the creator of the hash controls what happens when a key does not exist, with fetch you do.

7

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
3
  • 2
    h[:foo] is the same as h.fetch(:foo, nil). May 15, 2013 at 15:43
  • 1
    @LBg: it behaves the same, yes May 15, 2013 at 15:43
  • 10
    @LBg: No, it isn't. It is the same as 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.