If I had a list of balls, each of which has a color property. how can I get a list of balls with the most frequent color.
[m1,m2,m3,m4]
eg,
m1.color = blue m2.color = blue m3.color = red m4.color = blue
[m1,m2,m4] - list of balls with the most frequent color
My approach should 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 for the same color group. My implementation may be a mistake, and I feel that there must be a better and more reasonable way. any ideas please?
source share