count instances of an element inside an array in ruby

To count the instances of an element inside an array in Ruby, you can use the count method. This method takes an argument and returns the number of elements in the array that are equal to the argument.

Example:

main.rb
arr = [1, 2, 3, 2, 1, 2, 3, 3, 3]
count = arr.count(2)
puts count # Output: 3
78 chars
4 lines

In the above example, count variable will be set to the number of times 2 appears in the array.

Alternatively, you can also use the each_with_object method to count the instances of each element inside the array using a hash.

Example:

main.rb
arr = [1, 2, 3, 2, 1, 2, 3, 3, 3]
counts = arr.each_with_object(Hash.new(0)) { |element, counts| counts[element] += 1 }
puts counts # Output: {1=>2, 2=>3, 3=>4}
161 chars
4 lines

In the above example, the each_with_object method is used to iterate over the array and initialize a hash with default value of 0. For each element in the array, the count of that element is incremented in the hash. Finally, the counts hash contains the number of occurrences of each element in the array.

gistlibby LogSnag