简体   繁体   中英

Rails 5: How do I loop over a hash with each do

I want to get a specific output from the Typeform API.

This is the response I get back.

Example response:

"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
        }
       ]

Why does .first work and why does .second not work ?

My 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

You can do

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

or, if you want ids for example

answers.map { |answer| answer.dig(:field, :id) }

Because ruby hash doesn't have any second or last methods. You can access value with the help of keys. eg answer[:type], answer[:text]

item["answers"].each do |answer| was an overkill. The solution was as simple as that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM