Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Hash#fetch

(K arg0) -> V
[X] (K arg0, X arg1) -> (V | X)
[X] (K arg0) { (K arg0) -> X } -> (V | X)
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

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.3 · 3.2 · 3.1 · 3.0