I have the following array of hashes:
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}
]
Run Code Online (Sandbox Code Playgroud)
Out of this, how can I get an array, with the following:
[
{'author' => 'John Doe', 'total_sales' => 1200},
{'author' => 'George Doe', 'total_sales' => 1400}
]
Run Code Online (Sandbox Code Playgroud)
您可以使用each_with_object适当的默认值:
default = Hash.new {|h,k| h[k] = { 'author' => k, 'total_sales' => 0 } }
books.each_with_object(default) do |h, memo|
memo[h['author']]['total_sales'] += h['sales']
end.values
Run Code Online (Sandbox Code Playgroud)
输出:
[
{"author"=>"John Doe", "total_sales"=>1200},
{"author"=>"George Doe", "total_sales"=>1400}
]
Run Code Online (Sandbox Code Playgroud)