How to return all values of a hash in Ruby

Overview

We can use the values method to return all the values of a hash in Ruby.

Syntax

hash.values

Parameters

There are no parameters for the values method.

Return value

An array is returned which contains all values of Hash hash.

Example

Let’s look at the code below:

# create hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {name: "okwudili", stack: "ruby"}
h3 = {"foo": 0, "bar": 1}
h4 = {M:"Mango", A: "Apple", B: "Banana"}
# get the values of each
# hash and print result
puts "#{h1.values}"
puts "#{h2.values}"
puts "#{h3.values}"
puts "#{h4.values}"

Explanation

  • Lines 2 to 5: We create some hash and initialize them with keys and values.
  • Lines 9 to 12: We invoke the values method on the created hashes to get all their values. Then the results are printed to the console.

Free Resources