How to fetch some values of keys of a hash in Ruby

Overview

The fetch_values(*keys) method can be used to return the values that are associated with the given keys. It returns an array containing the values of the keys arguments keys that are passed to this method.

Syntax

hash.fetch_values(*keys)

Parameters

hash: This is the hash we want to access.

keys: These are the keys of the hash whose associated values we want to get. These values could either be one or more.

Return value

The value returned is an array containing the values that are associated with the specified keys keys.

Code example

# create hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {name: "okwudili", stack: "ruby"}
h3 = {"foo": 0, "bar": 1}
h4 = {foo: 0, bar: 1, baz: 2}
# get some values of some keys
puts "#{h1.fetch_values(:one, :one)}"
puts "#{h2.fetch_values(:name)}"
puts "#{h3.fetch_values(:foo, :bar)}"
puts "#{h4.fetch_values(:baz, :foo)}"

Code explanation

  • Lines 2–5: We create some hashes.
  • Lines 8–11: We fetch the values of some keys, using the fetch_values(*keys) method. Then, we print the results to the console.

Free Resources