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_values

(*::Hash::_Key keys) -> ::Array[V]
[K2 < ::Hash::_Key, T] (*K2 keys) { (K2 key) -> T } -> ::Array[V | T]
fetch_values(*keys) → new_array
fetch_values(*keys) {|key| ... } → new_array

When all given keys are found, returns a new array containing the values associated with the given keys:

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

When any given keys are not found and a block is given, calls the block with each unfound key and uses the block’s return value as the value for that key:

Example
h.fetch_values(:bar, :foo, :bad, :bam) {|key| key.to_s}
# => [1, 0, "bad", "bam"]

When any given keys are not found and no block is given, raises KeyError.

Related: see Methods for Fetching.

See also #fetch #filter #except #filter! also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0