How to check if an element exists in Array or not in Ruby with examples

The array contains a collection of elements, Sometimes we want to check if a given element exists in an array, resulting in a boolean values checks against conditional statements such as if-else.

How to check if an element exists in Array or not in Ruby with examples

There are multiple ways we can check key element exists in an array.

  • use the include? method

include? method checks element exists in an array, return true or false.

Here is an example program

words =  ['one', 'two', 'three']

puts words.include? "One" #=> false
puts words.include? "one" #=> true
  • using member? method

Hash member? checks for value exists or not in an array and return true or false.

If the elements exist, return true, else return false.

Here is an example program

words =  ['one', 'two', 'three']

puts words.member? "One" #=> false
puts words.member? "one" #=> true

  • use the index method

index? the method returns the first matched index position Here is an example program.

words =  ['one', 'two', 'three']

if words.index("one")
    puts "Exist"
end
puts words.index("one") #=> 0
puts words.index("two") #=> 1

  • use the count method The array count method returns the count of an element repeated in an array. It returns a duplicate count if found, else returns 0.
words =  ['one', 'two', 'three']

puts words.count("one") #=> 1
puts words.count("One") #=> 0

Conclusion

To summarize, There are multiple ways to check keys exist in hash objects with examples.