Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Hash#fetch

(::Hash::_Key key) -> V
[X] (::Hash::_Key key, X default_value) -> (V | X)
[K2 < ::Hash::_Key, X] (K2 key) { (K2 key) -> 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.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0