Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

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

abhilash

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
communitycreator
RELATED COURSES

View all Courses

Keep Exploring