Arrays 迭代到散列数组中
我试图循环到一个哈希数组中:Arrays 迭代到散列数组中,arrays,ruby,hash,each,Arrays,Ruby,Hash,Each,我试图循环到一个哈希数组中: response = [ { "element" => A, "group" => {"created" => 13, "code" => "Paris.rb", :"rsvp_limit" => 40}, "name" => "CODELAB", "venue" => {"id" => 17485302, "place" => "la cordée", "visibility
response = [
{
"element" => A,
"group" => {"created" => 13, "code" => "Paris.rb", :"rsvp_limit" => 40},
"name" => "CODELAB",
"venue" => {"id" => 17485302, "place" => "la cordée", "visibility" => "public"}
},
{
"element" => B,
"group" => {"created" => 13, "code" => "Paris.rb", :"rsvp_limit" => 40},
"name" => "PARISRB",
"venue" => {"id" => 17485302, "place" => "la cordée", "visibility" => "public"}
}
]
当我跑的时候
,它返回响应[0][“name”]
“CODELAB”
返回response[1][“name”]
“PARISRB”
response.each_with_index do |resp, index|
puts array[index]["name"]
end
这是我在控制台中遇到的错误:
NoMethodError: undefined method `[]' for nil:NilClass
from (pry):58:in `block in __pry__'
这里的
数组
似乎是输入错误。你的意思是:
response.each_with_index do |resp, index|
puts resp["name"]
end
不需要索引,因为resp
变量已正确初始化,以在每次迭代时包含哈希
因此可以简化为:
response.each do |resp|
puts resp["name"]
end
这里的
数组
似乎是输入错误。你的意思是:
response.each_with_index do |resp, index|
puts resp["name"]
end
不需要索引,因为resp
变量已正确初始化,以在每次迭代时包含哈希
因此可以简化为:
response.each do |resp|
puts resp["name"]
end
稍微短一点:
puts response.map{|hash| hash['name']}
# CODELAB
# PARISRB
稍微短一点:
puts response.map{|hash| hash['name']}
# CODELAB
# PARISRB
用英语写作时请使用英语标点符号。用英语写作时请使用英语标点符号。如果答案对你有用,@Ludivinecp,请接受它。如果这个答案对你有用,@Ludivinecp,那就接受它吧。这样你就能帮助那些帮助过你的人。