Rails 5:如何在每次循环中遍历哈希

时间:2019-04-03 13:30:56

标签: ruby-on-rails

我想从Typeform API获得特定的输出。

这是我得到的答复。

示例响应:

"answers": [
        {
          "field": {
            "id": "hVONkQcnSNRj",
            "type": "dropdown",
            "ref": "my_custom_dropdown_reference"
          },
          "type": "text",
          "text": "Job opportunities"
        },
        {
          "field": {
            "id": "RUqkXSeXBXSd",
            "type": "yes_no",
            "ref": "my_custom_yes_no_reference"
          },
          "type": "boolean",
          "boolean": false
        }
       ]

.first为什么起作用,为什么.second不起作用?

我的OrdersController.rb

  items = response.parsed_response["items"]
  items.each do |item|
    @order = current_user.orders.find_or_create_by(landing_id: item["landing_id"]) do |order|
      item["answers"].each do |answer|
      order.landing_id = item["landing_id"]
      order.email = item["hidden"]["email"]
      order.price = item["hidden"]["price"]
      order.moduls = item["hidden"]["moduls"]
      order.project = item["hidden"]["project"]
      order.website = answer.first # This works
      order.payment = answer.second # undefined method `second' for #<Hash:0x11f83e78>
    end
  end
end

3 个答案:

答案 0 :(得分:1)

您可以

answers.each { |answer| answer[:field] }

或者,例如,如果您想要ID

answers.map { |answer| answer[:field][:id] }

答案 1 :(得分:0)

因为ruby hash没有第二个或最后一个方法。您可以借助键访问值。例如答案[:类型],答案[:文本]

答案 2 :(得分:0)

item["answers"].each do |answer|是一个过大的杀伤力。解决方案就是这么简单:

order.website = item["answers"][1]["text] # Access the first field of answers array

order.payment = item["answers"][2]["text] # Access the second field of answers array