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 inarr. - Lines 4-6: We use the
include?()method to find out whether or notsearchStris present inarr. Based on the return value ofinclude?(), we print ifsearchStris present in the array or not.