Check if an Array Contains a Value using any? method
The any? method checks if any element in the array satisfies the given condition (usually using a block) and returns true
if at least one element satisfies the condition, otherwise false
.
Syntax:
array.any? { |element| condition }
Example: In this example we use the any?
method with a block to check if any element in the array equals 3
.Since 3
is present in the array, the puts
statement outputs true
and similarly do for other members present in the array
# Define an array
array = [1, 2, 3, 4, 5]
# Check if array contains a value using any? method
puts array.any? { |element| element == 3 } # Output: true
puts array.any? { |element| element == 6 } # Output: false
Output
true false
How to Check if an Array Contains a Value in Ruby?
In this article, we will discuss how to check if an array contains a specific value in ruby. We can check if an array contains a specific value through different methods ranging from using include? method and member?
method to any? method
Table of Content
- Check if an Array Contains a Value using include? method
- Check if an Array Contains a Value using member? method
- Check if an Array Contains a Value using any? method