我有一个Ruby的数组,看起来是这样的:将Ruby数组简化为唯一值计数的简洁方法?
animals = %w(dog cat bird cat dog bird bird cat)
我需要让每一个独特的物品的计数值在数组中。我可以这样做:
dogs = 0
cats = 0
birds = 0
animals.each do |animal|
dogs += 1 if animal == 'dog'
cats += 1 if animal == 'cat'
birds += 1 if animal == 'bird'
end
...但这种方法太冗长了。在Ruby中计算这些唯一计数的最简洁的方法是什么?
检查这里的答案做的另一种方式http://stackoverflow.com/questions/5470725/how-to-group-by-count-in-array-不使用循环 – Alireza 2014-10-27 19:04:28