How to check if a value exists in an Array in Ruby?
In this article, we will discuss how to check if a value exists in an array in ruby. We can check if a value exists in an array through different methods ranging from using Array#member? method and Array#include?
method to Array#any? method
Table of Content
- Check if a value exists in an array using Array#include?
- Check if a value exists in an array using Array#member?
- Check if a value exists in an array using Array#any?
Check if a value exists in an array using Array#include?
The Array#include?
method returns true if the array contains the specified value, otherwise false.
Syntax:
array.include?(value)
Example: In this example, we use array.include? method in the array to check if the array contains the value 3
.Since 3 is present in array 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 include? method
puts array.include?(3) # Output: true
puts array.include?(6) # Output: false
Output
true false
Check if a value exists in an array using Array#member?
The Array#member? method checks if the array contains the specified value and returns true
if it does, otherwise false
.
Syntax:
array.member?(value)
Example: In this example,we use member? method in the array to check if the array contains the value 3.Since 3 is present in array 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 member? method
puts array.member?(3) # Output: true
puts array.member?(6) # Output: false
Output
true false
Check if a value exists in an array using Array#any?
The Array#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
Contact Us