{

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to install and uninstall gem in Ruby Programming| Ruby on Rails by Example

How to do sum of array numbers in Ruby with examples

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to convert Class or Hash Object to JSON Object Ruby| Ruby on Rails By Example

How to remove duplicate elements from an array in Ruby with examples

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example