Felipe Maion Felipe Maion - 2 months ago 6
Ruby Question

Working with data inside the Hash

I am trying to build a system, for Personal Finance Management, with this I hope to learn Ruby.

I created a Stock < Asset.
This has all the information regarding the Asset (current spot price, etc).
And I have my Profile, where I am able to add the Asset to my Balance with the buying_price, quantities, dates, etc.

I would like to show_assets_by_code, and when I run this method, I want the system to go trough my Assest, and then classify this by code, and sum the Quantity, get the average_price with cost included. And return this: [asset, average_price_with_cost, total_quantity]

Right now I am able to group the assets:

{"RNGO11"=>
[{:quantity=>10,
:buying_price=>75.0,
:cost=>16.91,
:date=>2016-09-05 18:06:06 -0300,
:code=>"RNGO11",
:asset_id=>18563448},
{:quantity=>100,
:buying_price=>75,
:cost=>16.91,
:date=>"16/4/2015",
:code=>"RNGO11",
:asset_id=>18563448},
{:quantity=>100,
:buying_price=>77,
:cost=>16.91,
:date=>"16/4/2016",
:code=>"RNGO11",
:asset_id=>18563448}],
"BRCR11"=>
[{:quantity=>100,
:buying_price=>75,
:cost=>16.91,
:date=>2016-09-05 18:06:06 -0300,
:code=>"BRCR11",
:asset_id=>18563316}]}


How can I get the information, and work with the data inside the Hash for each group?

I want the output:

[RNGO11, quantity: 210, average_price: 75.34]
[BRCR11, quantity: 100, average_price: 75.17]


Any hint?

Answer
data.map do |key, values|
  quantity = values.map { |entry| entry[:quantity] }.reduce(:+)
  average_price = values.map { |entry| entry[:buying_price] + entry[:cost] }.reduce(:+).to_f / values.size
  { code: key, quantity: quantity, average_price: average_price }
end

Let me know if this works for you Edit: added cost into consideration

Comments