Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
hash
communitycreator

How to check if a particular value exists in a Hash in Ruby

okwudili onyejiaku

Overview

A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false.

Syntax

hash.has_value?(value)

Parameters

hash: The hash we want to use for checking.

value: The value we want to confirm if present in the hash.

Return value

This method returns a Boolean. true is returned if such value exists. Otherwise, false is returned.

# 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 values
puts h1.has_value?(2)
puts h2.has_value?("ruby")
puts h3.has_value?("foo")
puts h4.has_value?("Apple")
Check for some values in a Hash

Explanation

  • Lines 2-5: We create several hashes.

  • Lines 8-11: We check if some values existed in the hashes we created and print the results to the console.

RELATED TAGS

ruby
hash
communitycreator
RELATED COURSES

View all Courses

Keep Exploring