Skip to content
instance method

Hash#fetch

(K arg0) -> V
[X] (K arg0, X arg1) -> (V | X)
[X] (K arg0) { (K arg0) -> X } -> (V | X)
fetch(key) → object
fetch(key, default_value) → object
fetch(key) {|key| ... } → object

With no block given, returns the value for the given key, if found;

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

If the key is not found, returns default_value, if given, or raises KeyError otherwise:

Example
h.fetch(:nosuch, :default) # => :default
h.fetch(:nosuch)           # Raises KeyError.

With a block given, calls the block with key and returns the block’s return value:

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

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

Related: see Methods for Fetching.

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