我有以下散列数组:
books = [
{'author' => 'John Doe', 'month' => 'June', 'sales' => 500},
{'author' => 'George Doe', 'month' => 'June', 'sales' => 600},
{'author' => 'John Doe', 'month' => 'July', 'sales' => 700},
{'author' => 'George Doe', 'month' => 'July', 'sales' => 800}
]
在此基础上,如何获得具有以下内容的数组:
[
{'author' => 'John Doe', 'total_sales' => 1200},
{'author' => 'George Doe', 'total_sales' => 1400}
]
您可以使用Hash#update(aka merge!
)的形式,该形式采用一个块来确定要合并的两个哈希中存在的键的值:
books.each_with_object({}) do |g,h|
h.update(g['author']=>g['sales']) { |_,o,n| o+n }
end.map { |k,v| { 'author'=>k, 'total_sales'=>v } }
#=> [{"author"=>"John Doe", "total_sales"=>1200},
# {"author"=>"George Doe", "total_sales"=>1400}]
有关块变量的说明,请参见文档_
,o
以及n
。(我使用_
了公共密钥,主要是向读者传达信号,它没有在块计算中使用,这是一种常见的Ruby约定。)
考虑在构建散列之后停止:
books.each_with_object({}) do |g,h|
h.update(g['author']=>g['sales']) { |_,o,n| o+n }
end
#=> {"John Doe"=>1200, "George Doe"=>1400}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句