Skip to content

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

instance method

Hash#fetch_values

(*K) -> ::Array[V]
[X] (*K) { (K) -> X } -> ::Array[V | X]
hash.fetch_values(*keys) → new_array
hash.fetch_values(*keys) {|key| ... } → new_array

Returns a new Array containing the values associated with the given keys *keys:

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

Returns a new empty Array if no arguments given.

When a block is given, calls the block with each missing key, treating the block’s return value as the value for that key:

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

When no block is given, raises an exception if any given key is not found.

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