Suppose I have the following class, product.rb:
require 'yaml'
class Product
attr_accessor :id, :price
def initialize args = {}
options = {:id => "", :price => 0}.merge(args)
self.id, self.price = options[:id], options[:price]
end
def inspect
self.to_yaml
end
end
And the following example program, example.rb:
require_relative 'product'
products = Array.new
(1..5).each do |n| # Create 5 products with random id and price
products << Product.new(
:id => rand(1..5),
:price => rand(10..50))
end
products.each { |p| puts p.inspect }
Example output from running example.rb:
C:\>ruby example.rb
--- !ruby/object:Product
id: 3
price: 48
--- !ruby/object:Product
id: 2
price: 47
--- !ruby/object:Product
id: 5
price: 32
--- !ruby/object:Product
id: 5
price: 49
--- !ruby/object:Product
id: 3
price: 33
The result is an array of objects of type Product, with duplicate ids.
How can I create a hash with id as the key and the sum of price as the value?
Example of desired result:
{ "2" => 47, "3" => 81, "5" => 81 } # { id => sum of price }