Trusted answers to developer questions

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

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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.

RELATED TAGS

ruby
Did you find this helpful?