What is the hash.key?() method in Ruby?

Overview

In Ruby, the hash.key?() method is used to check if a given key exists in a hash.

Syntax

hash.key?(keyToFind)

Parameters

This method takes keyToFind as a parameter. It is the key we want to check.

Return value

It returns a boolean value. It returns true if the key exists. Otherwise, it returns false.

Example

# 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"}
# check if key exists
# and print results
puts h1.key?(:one)
puts h2.key?(:name)
puts h3.key?(:foo)
puts h4.key?(:C)

Explanation

  • Lines 2–5: We create some hashes.

  • Lines 9–12: We check if some keys exist in the hashes. Next, we print the results to the console.

Free Resources