How can we access the entries of a Hash in Ruby?

Overview

We can get the value of a given key of a Hash by using the fetch(key) method. We only need to specify the key we want to get. This way, it will give us the value of the key we have specified.

Syntax

hash.fetch(key)

Parameters

hash: This is the Hash whose keys we want to access.

key: This is the key whose value will be returned, if found.

Return value

This method returns the value for the given key.

Code example

# create hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {name: "okwudili", stack: "ruby"}
h3 = {"foo": 0, "bar": 1}
h4 = { a: 100, b: 200, c: 300 }
# find key values
puts h1.fetch(:two)
puts h2.fetch(:name)
puts h3.fetch(:foo)
puts h4.fetch(:b)

Code explanation

  • Lines 2–5: We create some Hashes.
  • Lines 8–11: We invoke the fetch(key) method on the Hashes, along with the arguments of the method. Then, we print the results to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources