2012-03-22 108 views
0

我有這個工作與複雜的陣列:如何訪問哈希

[ 
    ["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

考慮爲這種事情創建自己的'類' - 更具可讀性。 – Reactormonk 2012-03-22 15:35:36

回答

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 

當你有不同的元素不同的結構本可以處理得有些更復雜的情況。

+0

正是我所需要的,謝謝。 – Josh 2012-03-22 15:42:52

+0

這就是我最終做的 - 'apps = apps.flatten apps = apps.delete_if do | key,value | key.class ==字符串結尾 apps.each do | app |放棄結束' – Josh 2012-03-22 15:55:28

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