Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Hash#fetch

hash.fetch(key) → object
hash.fetch(key, default_value) → object
hash.fetch(key) {|key| ... } → object

Returns the value for the given key, if found.

Example
h = {foo: 0, bar: 1, baz: 2}
h.fetch(:bar) # => 1

If key is not found and no block was given, returns default_value:

Example
{}.fetch(:nosuch, :default) # => :default
{}.fetch(:nosuch) # => nil

If key is not found and a block was given, yields key to the block and returns the block’s return value:

Example
{}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"

Raises KeyError if neither default_value nor a block was given.

Note that this method does not use the values of either default or default_proc.

See also #except #fetch_values #eql? #filter also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1