[英]Rails 5: How do I loop over a hash with each do
I want to get a specific output from the Typeform API. 我想从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 ? 为什么
.first
的工作,为什么.second
不行?
My OrdersController.rb
我的
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 或者,例如,如果您想要ID
answers.map { |answer| answer.dig(:field, :id) }
Because ruby hash doesn't have any second or last methods. 因为ruby哈希没有任何第二个或最后一个方法。 You can access value with the help of keys.
您可以借助键访问值。 eg answer[:type], answer[:text]
例如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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.