如何在使用序列化时构建哈希?

时间:2015-03-03 22:55:56

标签: ruby-on-rails ruby-on-rails-4 mechanize

如何在使用序列化时构建哈希?

{
  amount => [{year => total_cost}],
  amount => [{year => total_cost}],
  amount => [{year => total_cost}]
}

1 个答案:

答案 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