My question
Here, I have 2 arrays and 1 hash,
@key_array = %w(year entry amount)
@nums = {
"sales": [1000, 2000, 3000, 4000],
"net_income": [20, 30, 50, 60],
}
@years = [2011, 2012, 2013, 2014]
What I would like to do is to turn those 3 into like this
[{"year"=>2011, "entry"=>:sales, "amount"=>1000},
{"year"=>2012, "entry"=>:sales, "amount"=>2000},
{"year"=>2013, "entry"=>:sales, "amount"=>3000},
{"year"=>2014, "entry"=>:sales, "amount"=>4000},
{"year"=>2011, "entry"=>:net_income, "amount"=>20},
{"year"=>2012, "entry"=>:net_income, "amount"=>30},
{"year"=>2013, "entry"=>:net_income, "amount"=>50},
{"year"=>2014, "entry"=>:net_income, "amount"=>60}]
So far, I have tried this Ruby code...
def build_entry_nums_hash
num_arr = []
@years.each do |year|
@nums.each do |key, value|
value.each do |fin|
value_array = [year, key, fin]
hash = {}
@key_array.zip(value_array).each { |k, v| hash[k] = v }
num_arr << hash
end
end
end
num_arr
end
It returns almost what I expected, but a bit wrong. It returns some unnecessary hashes.
[{"year"=>2011, "entry"=>:sales, "amount"=>1000},
{"year"=>2011, "entry"=>:sales, "amount"=>2000},
{"year"=>2011, "entry"=>:sales, "amount"=>3000},
{"year"=>2011, "entry"=>:sales, "amount"=>4000},
......
{"year"=>2014, "entry"=>:net_income, "amount"=>20},
{"year"=>2014, "entry"=>:net_income, "amount"=>30},
{"year"=>2014, "entry"=>:net_income, "amount"=>50},
{"year"=>2014, "entry"=>:net_income, "amount"=>60}]
Would you give me some advice?
Current situation
I am not sure this is necessary, so please read through if you concerned why I have to convert those arrays and hash into one hash.
I am trying to parse some financial data from an website by using Nokogiri. The data is written in HTML Table tag and it looks like an Excel spreadsheet. My goal is to display those data by using my rails. Currently, I was able to get the numbers and struggling how could I put them into rails DB. It's good if I could do like..
Findata.create{"year"=>2011, "entry"=>:sales, "amount"=>1000}
Sine it was very easy to get the financial numbers in row, I made a hahs like @num. What I need is to mix up other 2 arrays and get a hash what I need.
Edit: I have corrected mistakes in array with hash