To check if a specified element is present in an array in Ruby, you can use methods like include?
or a loop to iterate through the array and check each element.
In this example,
numbers
with values 10, 20, 30, 40, 50.include?
method to check if element 30 is present in the array.include?
method returns true if the element is found, otherwise false.numbers = [10, 20, 30, 40, 50]
element = 30
is_present = numbers.include?(element)
puts "Element 30 is present: #{is_present}"
Element 30 is present: true
In this example,
fruits
with values 'apple', 'banana', 'cherry'.for
loop to iterate through the array and check each element with the specified element 'banana'.found
to true; otherwise, it remains false.fruits = ['apple', 'banana', 'cherry']
element = 'banana'
found = false
fruits.each do |fruit|
if fruit == element
found = true
break
end
end
puts "Element 'banana' is present: #{found}"
Element 'banana' is present: true
In this tutorial, we learned How to check if Specified Element is present in the Array in Ruby language with well detailed examples.