2
我在帮助this question的答案,它引发了我自己的问题。计算Ruby中每个唯一对象属性的对象总数
Pie
是具有pieces
阵列制成的PiePiece
对象中的对象。- 每个
PiePiece
有flavor
属性
如何创建一个哈希看起来像这样:
# flavor => number of pieces
{
:cherry => 3
:apple => 1
:strawberry => 2
}
这工作,但我认为还可以提高
def inventory
hash = {}
pieces.each do |p|
hash[p.flavor] ||= 0
hash[p.flavor] += 1
end
hash
end
有任何想法吗?
不错。从来不知道group_by存在。 – bergyman 2010-04-12 22:18:39
Ruby 1.8.7是新的。如果使用1.8.6,只需“需要”backports“'”。顺便说一句,'哈希[key_value_pairs]'也是1.8.7的新手 – 2010-04-12 22:42:58
使用Ruby 1.9,谢谢:) – 2010-04-13 03:29:37