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.
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.
There are multiple ways we can check key element exists in an array.
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
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
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
words = ['one', 'two', 'three']
puts words.count("one") #=> 1
puts words.count("One") #=> 0
To summarize, There are multiple ways to check keys exist in hash objects with examples.
🧮 Tags
Recent posts
Nodejs package.json resolutions How to find Operating System username in NodeJS? How to convert Double to Integer or Integer to double in Dart| Flutter By Example Ways to skip test case execution in Gradle project build Learn Gradle | tutorials, and examplesRelated posts