Using the same example:
Name = Struct.new(:first_name, :last_name) do
def greeting
"Hello #{first_name}!"
end
end
full_names = [
Name.new("a", "b"),
Name.new("b", "c"),
Name.new("d", "c"),
Name.new("c", "d"),
Name.new("d", "c"),
Name.new("b", "b"),
Name.new("b", "e")
]
We can use inject
to create a Hash with first_name => frequency
:
first_names = full_names.map(&:first_name)
first_names #["a", "b", "d", "c", "d", "b", "b"]
hash_of_frequency = first_names.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
hash_of_frequency # [["b", 3], ["d", 2], ["a", 1], ["c", 1]]
Now we just execute a sort_by
and get your results:
hash_of_frequency.sort_by{|k, v| -v}.first(number_desired)
The result is the same, but I've preferred to use inject