如何在使用序列化时构建哈希?
{
amount => [{year => total_cost}],
amount => [{year => total_cost}],
amount => [{year => total_cost}]
}
答案 0 :(得分:0)
试试这段代码。它混合使用.map
和.each_with_object
来获取您描述的哈希和数组混合:
namespace :data do
task scrap: :environment do
agent = Mechanize.new
results = (3000..25000).step(1000).each_with_object({}) do |amount, h|
year_costs = (1..5).step(1).map do |year|
total_cost = agent.get("https://www.cashbuddy.se/api/loancost?amount=#{amount}&numberOfYears=#{year}").body
{year => total_cost}
end # => an array of hashes, as in your question.
h[amount] = year_costs
end
Credit.create(credit_data: results)
end
end