What is the member?() method of hash in Ruby?

Overview

In Ruby, the member?() method of a hash is used to check if a certain key value is present in the hash.

Syntax

hash.member?(key)

Parameters

This method takes the parameter, key, which represents the key we want to check in the hash.

Return value

It returns a boolean value; true if the key exists and false if it doesn’t.

Example

# create some 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 some keys exists
puts h1.member?(:one)
puts h2.member?(:stack)
puts h3.member?(:bar)
puts h4.member?(:D)

Explanation

  • Line 2–5: We create the hashes h1, h2, h3, and h4.
  • Line 8–11: We use the member?() method to check if some keys exist in the hashes. Next, we print the results to the console.

Free Resources