2010-04-12 37 views
2

我在帮助this question的答案,它引发了我自己的问题。计算Ruby中每个唯一对象属性的对象总数

  1. Pie是具有pieces阵列制成的PiePiece对象中的对象。
  2. 每个PiePieceflavor属性

如何创建一个哈希看起来像这样:

# 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 

有任何想法吗?

回答

5
def inventory 
    Hash[pieces.group_by(&:flavor).map{|f,p| [f, p.size]}] 
end 
+0

不错。从来不知道group_by存在。 – bergyman 2010-04-12 22:18:39

+0

Ruby 1.8.7是新的。如果使用1.8.6,只需“需要”backports“'”。顺便说一句,'哈希[key_value_pairs]'也是1.8.7的新手 – 2010-04-12 22:42:58

+0

使用Ruby 1.9,谢谢:) – 2010-04-13 03:29:37