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.rb78 chars4 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.rb161 chars4 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