Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hash
ruby
communitycreator

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

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
Using the include?() method to check if a key exists in a Hash

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.

RELATED TAGS

hash
ruby
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring