frequency of objects in an array using Ruby
arrays, ruby
Solution
Your code isn't bad, but it is inefficient. If I were you I would seek a solution that iterates through your array only once, like this:
balls = [m1, m2, m3, m4]
most_idx = nil
groups = balls.inject({}) do |hsh, ball|
hsh[ball.color] = [] if hsh[ball.color].nil?
hsh[ball.color] << ball
most_idx = ball.color if hsh[most_idx].nil? || hsh[ball.color].size > hsh[most_idx].size
hsh
end
groups[most_idx] # => [m1,m2,m4]
This does basically the same thing as `group_by`, but at the same time it counts up the groups and keeps a record of which group is largest (`most_idx`).
Problem
If i had a list of balls each of which has a color property. how can i cleanly get the list of balls with the most frequent color. ``` [m1,m2,m3,m4] ``` say, ``` m1.color = blue m2.color = blue m3.color = red m4.color = blue ``` `[m1,m2,m4]` is the list of balls with the most frequent color My Approach is to do: ``` [m1,m2,m3,m4].group_by{|ball| ball.color}.each do |samecolor| my_items = samecolor.count end ``` where count is defined as ``` class Array def count k =Hash.new(0) self.each{|x|k[x]+=1} k end end ``` my_items will be a hash of frequencies foreach same color group. My implementation could be buggy and i feel there must be a better and more smarter way. any ideas please?