迭代到哈希数组

Iterate into an array of hash

我正在尝试循环到哈希数组中:

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

当我运行

如何创建一个循环来获取此哈希数组的每个元素的名称?

我试过了:

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__'

这里的array好像打错了。你的意思是:

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