迭代到一个哈希数组

时间:2016-03-09 14:20:28

标签: arrays ruby hash each

我正在尝试循环使用哈希数组:

string

当我跑步时

  • 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[0]["name"]

  • "CODELAB"返回response[1]["name"]

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

我试过了:

"PARISRB"

这是我在控制台中遇到的错误:

response.each_with_index do |resp, index|
  puts array[index]["name"]
end

2 个答案:

答案 0 :(得分:3)

这里的array似乎是一个错字。你的意思是:

response.each_with_index do |resp, index|
  puts resp["name"]
end

不需要索引,因为resp变量已正确初始化以包含每次迭代时的散列。

因此可以简化为:

response.each do |resp|
  puts resp["name"]
end

答案 1 :(得分:3)

稍微短一些:

puts response.map{|hash| hash['name']}
# CODELAB
# PARISRB