How could I Turn 2 arrays and 1 hash into single hash by Ruby? -
my question
here, have 2 arrays , 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 turn 3 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, have tried ruby code...
def build_entry_nums_hash num_arr = [] @years.each |year| @nums.each |key, value| value.each |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 expected, bit wrong. returns 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 give me advice?
current situation
i not sure necessary, please read through if concerned why have convert arrays , hash 1 hash.
i trying parse financial data website using nokogiri. data written in html table tag , looks excel spreadsheet. goal display data using rails. currently, able numbers , struggling how put them rails db. it's if like..
findata.create{"year"=>2011, "entry"=>:sales, "amount"=>1000}
sine easy financial numbers in row, made hahs @num. need mix other 2 arrays , hash need.
edit: have corrected mistakes in array hash
arr = [] @nums.each |num_key, num_arr| @years.each_with_index |year,i| arr << {"year" => year, "entry" => num_key.to_sym, "amount" => num_arr[i]} end end;arr
gives me
[{"amount"=>20, "entry"=>:net_income, "year"=>2011}, {"amount"=>30, "entry"=>:net_income, "year"=>2012}, {"amount"=>50, "entry"=>:net_income, "year"=>2013}, {"amount"=>60, "entry"=>:net_income, "year"=>2014}, {"amount"=>1000, "entry"=>:sales, "year"=>2011}, {"amount"=>2000, "entry"=>:sales, "year"=>2012}, {"amount"=>3000, "entry"=>:sales, "year"=>2013}, {"amount"=>4000, "entry"=>:sales, "year"=>2014}]
edit: put ";arr" after loop you're left arr
variable holds hashes.
Comments
Post a Comment