Open In App

How to Check if an Array Contains a Value in Ruby?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

Check if an Array Contains a Value using include? method

The  include? method checks if the array contains the specified value and returns true if it does, otherwise false.

Syntax:

array.include?(value)

Example: In this example, we use 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

Ruby
# 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 an Array Contains a Value using member? method

The 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

Ruby
# 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 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

Ruby
# 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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads