计算 Ruby 中每个唯一对象属性的对象总和
我正在帮助回答这个问题 这引发了我自己的一个问题。
Pie
是一个对象,它具有由PiePiece
对象组成的pieces
数组。- 每个
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
有什么想法吗?
I was helping with an answer in this question and it sparked a question of my own.
Pie
is an object that has apieces
array made of ofPiePiece
objects.- Each
PiePiece
has aflavor
attribute
How do I create a hash that looks like this:
# flavor => number of pieces
{
:cherry => 3
:apple => 1
:strawberry => 2
}
This works, but I think it could be improved
def inventory
hash = {}
pieces.each do |p|
hash[p.flavor] ||= 0
hash[p.flavor] += 1
end
hash
end
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)