【发布时间】:2014-10-28 03:13:49
【问题描述】:
我有一个看起来像这样的 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 中计算这些唯一计数的最简洁方法是什么?
【问题讨论】: