使用序列化时如何构建哈希?
{
amount => [{year => total_cost}],
amount => [{year => total_cost}],
amount => [{year => total_cost}]
}
最佳答案
试试这个代码。它混合 .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
关于ruby-on-rails - 使用序列化时如何构建哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843622/