fetch(p1, p2 = v2) public

Returns a value from the hash for the given key. If the key can’t be found, there are several options: With no other arguments, it will raise an KeyError exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned.

h = { "a" => 100, "b" => 200 }
h.fetch("a")                            #=> 100
h.fetch("z", "go fish")                 #=> "go fish"
h.fetch("z") { |el| "go fish, #{el}"}   #=> "go fish, z"

The following example shows that an exception is raised if the key is not found and a default value is not supplied.

h = { "a" => 100, "b" => 200 }
h.fetch("z")

produces:

prog.rb:2:in `fetch': key not found (KeyError)
 from prog.rb:2
Show source
Register or log in to add new notes.
February 4, 2016
0 thanks

Fetch with default value

You can specify default value as a fail-back if a hash doesn’t have a given key.

{a: false}.fetch(:b, true)
=> true
{a: false}.fetch(:a, true)
=> false

It is useful especially in the case where you want to set default value for a method.

def initialize(args)
  @foo = args.fetch(:foo, 1)
  @bar = args.fetch(:bar, 2)

  # This can take over the following way.
  # `@bar = args[:bar] || 2` 
  # => @bar is overwritten if caller specifies nil for :bar!
end