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
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts