使用序列化时如何构建哈希?
how do I build a hash when using serialization?
如何在使用序列化时构建哈希?
{
amount => [{year => total_cost}],
amount => [{year => total_cost}],
amount => [{year => total_cost}]
}
试试这个代码。它混合 .map
and .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
如何在使用序列化时构建哈希?
{
amount => [{year => total_cost}],
amount => [{year => total_cost}],
amount => [{year => total_cost}]
}
试试这个代码。它混合 .map
and .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