What is include?() method of a Hash in Ruby?

Overview

The include?() method of a hash is used to check if a certain key passed to it as an argument is contained in a particular hash.

Syntax

hash.include?(key)

Parameters

hash: The hash we want to use and check for keys present.

key: The key we want to check if it exists in the hash.

Return value

This method returns true if the key is present in the hash. Otherwise, it returns false.

Example

Let’s look at the example 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"}
# check for some keys
puts h1.include?(:one)
puts h2.include?(:name)
puts h3.include?(:foobar)
puts h4.include?(:C)

Explanation

  • Lines 2 to 5: We create some hash values.
  • Lines 8 to 11: We use the include?() method to check if some keys exist in the hashes, and print the results to the console.