find the mode of all elements in an array in ruby

To find the mode of all elements in an array in Ruby, you can first count the frequency of each element in the array using a hash, and then return the elements with the highest frequency.

Here's an example implementation of the method:

main.rb
def mode(array)
  frequency = Hash.new(0)
  array.each { |element| frequency[element] += 1 }
  frequency.select { |_, count| count == frequency.values.max }.keys
end
166 chars
6 lines

This method first initializes an empty hash with a default value of zero. It then iterates over each element in the array and increments the count for that element in the hash.

Finally, it returns the keys of the hash with the highest value (frequency). If there are multiple elements with the same maximum frequency, all of them will be returned.

Here's an example usage of the mode method:

main.rb
arr = [0, 2, 2, 3, 3, 3]
mode(arr) #=> [3]
43 chars
3 lines

In this example, the mode of the array [0, 2, 2, 3, 3, 3] is 3, which is returned by the mode method.

related categories

gistlibby LogSnag