Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 迭代到散列数组中_Arrays_Ruby_Hash_Each - Fatal编程技术网

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,那就接受它吧。这样你就能帮助那些帮助过你的人。