OneBite.Dev - Coding blog in a bite size

search for a specific element in an array in Ruby

Code snippet on how to search for a specific element in an array in Ruby

arr = [1, 2, 3, 4, 5]
search_element = 3

arr.each do |el|
  if el == search_element
    puts "Element #{search_element} found!"
  end
end

This sample code searches for a specific element in an array. First, we create an array arr of five elements, then we assign the element we are searching for to the variable search_element. We then use the each method to loop through each element in the array, and the if statement to check if the current element is equal to the search_element. If they match, then we output the message “Element #{search_element} found!“. The curly braces are used to interpolate the contents of the search_element variable into the string.

ruby