OneBite.Dev - Coding blog in a bite size

count the number of occurrences of a specific element in an array in Ruby

Code snippet on how to count the number of occurrences of a specific element in an array in Ruby

  elements = [2, 4, 6, 8, 2, 4]
  search_element = 2
  count = 0
  elements.each do |el|
    if el == search_element
      count += 1
    end
  end
  puts count

This code counts the number of occurrences of a specific element in an array. It starts by declaring an array of elements and then a search element. The code also declares a count variable and sets it to 0. Next, using the each loop, the code iterates through each element of the array. Within the loop, it checks if the element is the same as our search element. If the condition is met, then the count variable is increased by one. Finally, the count is printed to the console.

ruby