将Ruby数组减少到唯一值计数的简明方法?

And*_*rew 0 ruby arrays unique count

我有一个类似于这样的Ruby数组:

animals = %w(dog cat bird cat dog bird bird cat)
Run Code Online (Sandbox Code Playgroud)

我需要计算数组中每个唯一项的计数.我可以这样做:

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
Run Code Online (Sandbox Code Playgroud)

......但这种做法过于冗长.在Ruby中计算这些独特计数的最简洁方法是什么?

Sur*_*rya 5

我猜你要找的是count:

animals = %w(dog cat bird cat dog bird bird cat)
dogs = animals.count('dog') #=> 2
cats = animals.count('cat') #=> 3
birds = animals.count('bird') #=> 3
Run Code Online (Sandbox Code Playgroud)