How to check if a value exists in an array in Ruby

Overview

The include?() method checks whether or not the given object is present in the array.

Syntax

Array.include?(obj)

Parameter

  • obj: This the object to check.

Return value

The method returns true if the given object is present in the array. Otherwise, it returns false.

Example

arr = [ "educative", "edpresso", "courses", "shots" ]
searchStr = "educative"
puts arr.include?(searchStr)?
"#{searchStr} is present in the array" :
"#{searchStr} is not present in the array"
searchStr = "hello"
puts arr.include?(searchStr)?
"#{searchStr} is present in the array" :
"#{searchStr} is not present in the array"

Explanation

  • Line 1: We define an array of strings called arr.
  • Line 3: We define the object/string, i.e., searchStr, that needs to be checked for its presence in arr.
  • Lines 4-6: We use the include?() method to find out whether or not searchStr is present in arr. Based on the return value of include?(), we print if searchStr is present in the array or not.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources