find the mode of all values in a map in ruby

To find the mode of all values in a Ruby map, also known as a hash, we can use the group_by method from the Enumerable module. The group_by method will group all the values in the map by their frequency, then we can use the max_by method to find the most frequently occurring value.

Here is an example implementation:

main.rb
def mode(map)
  frequencies = map.values.group_by(&:itself)
  mode_frequency = frequencies.values.max_by(&:size)
  mode_frequency.first
end
140 chars
6 lines

In this implementation, the map argument is a Ruby hash. We first retrieve all the values from the map using the values method, then group them by their frequency using the group_by method and the itself method as the grouping key.

We then find the most frequently occurring value by calling max_by on the values array of frequencies. The size method is used to calculate the size of each frequency group. max_by returns the group with the highest size, which corresponds to the most frequently occurring value.

Finally, we return the most frequently occurring value, which is the first value in the mode_frequency array.

Here is an example usage of the mode method:

main.rb
ages = {
  "jane" => 25,
  "john" => 30,
  "jerry" => 25,
  "jim" => 28,
  "jess" => 25
}

mode_age = mode(ages)
puts "The mode age is #{mode_age}" #=> The mode age is 25
171 chars
11 lines

In this example, we have a map of ages for 5 people. The mode age is 25, which is returned by the mode method.

gistlibby LogSnag