To count the number of occurrences of a specified element in an array in Ruby, you can use methods like count, select, or a loop to iterate through the array and count each occurrence.
In this example,
numbers
with values 10, 20, 30, 40, 30, 50.count
method on the array to count occurrences of element 30.numbers = [10, 20, 30, 40, 30, 50]
puts "Number of occurrences of element 30: #{numbers.count(30)}"
Number of occurrences of element 30: 2
In this example,
fruits
with values 'apple', 'banana', 'cherry', 'banana'.select
method on the array to select elements equal to 'banana'.size
method on the selected array to get the count of occurrences of 'banana'.fruits = ['apple', 'banana', 'cherry', 'banana']
count = fruits.select { |fruit| fruit == 'banana' }.size
puts "Number of occurrences of element 'banana': #{count}"
Number of occurrences of element 'banana': 2
In this tutorial, we learned How to count the Number of Occurrences of Specified Element in the Array in Ruby language with well detailed examples.