I'm working to better understand hashes, and I've come across problems in which I have a collection with duplicate items and I need to return a hash of those items de-duped while adding a key that counts those items. For example...
I have a hash of grocery items and each item points to another hash that describes various attributes of each item.
groceries = [
{"avocado" => {:price => 3.0, :on_sale => true}},
{"tomato" => {:price => 1.0, :on_sale => false}},
{"avocado" => {:price => 3.0, :on_sale => true}},
{"kale" => {:price => 5.0, :on_sale => false}}
]
And I want my updated groceries to be...
groceries_updated = {
"avocado" => {:price => 3.0, :on_sale => true, :count => 2},
"tomato" => {:price => 1.0, :on_sale => false, :count => 1},
"kale" => {:price => 5.0, :on_sale => false, :count => 1}
}
My initial approach was first create my new hash by iterating through the original hash so I would have something like this. Then I would iterate through the original hash again and increase the counter in my new hash. I'm wondering if this can be done in one iteration of the hash. I've also tried using the #each_with_object method, but I also need a better understanding of the parameters. My attempt with #each_with_object results in an array of hashes with the :count key added, but no consolidation.
def consolidate_cart(array)
array.each do |hash|
hash.each_with_object(Hash.new {|h,k| h[k] = {price: nil, clearance: nil, count: 0}}) do |(item, info), obj|
puts "#{item} -- #{info}"
puts "#{obj[item][:count] += 1}"
puts "#{obj}"
end
end
end