How to check if a hash contains a particular key in Ruby

Overview

We can check if a particular hash contains a particular key by using the method has_key?(key). It returns true or false depending on whether the key exists in the hash or not.

Syntax

hash.has_key?(key)

Parameters

hash: This is the hash we want to access the keys of.

key: This is the key we want to check to see if hash hash contains it.

Return value

true is returned if the hash, hash, contains the key, key. Otherwise, a false is returned.

Code 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 for some keys
puts h1.has_key?(:one)
puts h2.has_key?(:name)
puts h3.has_key?(:foobar)
puts h4.has_key?(:C)

Explanation

  • Lines 2-5: We create the hashes h1, h2, h3, andh4.
  • Lines 8-11: We check some keys to see if they were contained in some hashes. We then print the results to the console.

Free Resources