我可以使用它:
[
["app1", {"name"=>"name1", "path"=>"xyz.com/"}],
["app2", {"name"=>"name2", "path"=>"xyz.com/"}],
["app3", {"name"=>"name3", "path"=>"xyz.com/"}],
# etc.
]
我希望能够访问每个名称和路径,所以我尝试了:
apps.each do |key, value|
value.each do |key, value|
puts value
end
end
但这会返回一个枚举器。知道我怎么能这样做吗?
答案 0 :(得分:1)
apps = [["app1", {"name"=>"name1", "path"=>"https://xyz.com/"}], ["app2", {"name"=>"name2", "path"=>"https:/xyz.com/"}], ["app3", {"name"=>"name3", "path"=>"https://xyz.com/"}]]
apps.flatten.each do |t|
next unless t.class == Hash
next unless t.key?("name")
next unless t.key?("path")
puts t.inspect # now t is a hash that has both "name" and "path" keys - do what you want
end
当你有不同元素的不同结构时,这将处理更复杂的情况。
答案 1 :(得分:0)
我认为你的第一个循环只是循环遍历一个数组,所以它将是:
apps.each do |app|
app.each do |key, value|
puts key # would be app1 in the first array
puts value["name"]
puts value["path"]
end
end
答案 2 :(得分:0)
ar = [
["app1", {"name"=>"name1", "path"=>"xyz.com/"}],
["app2", {"name"=>"name2", "path"=>"xyz.com/"}],
["app3", {"name"=>"name3", "path"=>"xyz.com/"}]
]
#Get a specific app:
p ar.assoc("app2").last["name"]
#Get all names and paths
ar.each{|app| name, path = app.last["name"], app.last["path"]}