2014-02-17 65 views
1

我的代碼塊:如何正確訪問和遍歷Ruby中的多維數組?

super_heroes = [ 
    ["Spider Man", "Peter Parker"], 
    ["Deadpool", "Wade Wilson"], 
    ["Wolverine", "James Howlett"] 
] 

super_heroes.each do |sh| 
    sh.each do |heroname, realname| 
     puts "#{realname} is #{heroname}" 
    end 
end 

輸出是這樣的:

is Spider Man 
is Peter Parker 
is Deadpool 
is Wade Wilson 
is Wolverine 
is James Howlett 

,但我想是這樣的:

Peter Parker is Spider Man 
Deadpool is Wade Wilson 
Wolverine is James Howlett 

後迭代代碼的時間,我仍然無法弄清楚。如果有人能把我放在正確的方向並解釋我做錯了什麼,我將不勝感激。謝謝!

回答

4

如下活動:

super_heroes = [ 
    ["Spider Man", "Peter Parker"], 
    ["Deadpool", "Wade Wilson"], 
    ["Wolverine", "James Howlett"] 
] 

super_heroes.each do |heroname, realname| 
    puts "#{realname} is #{heroname}" 
end 

# >> Peter Parker is Spider Man 
# >> Wade Wilson is Deadpool 
# >> James Howlett is Wolverine 

什麼與您的代碼發生了什麼?

super_heroes.each do |sh| # sh is ["Spider Man", "Peter Parker"] etc.. 
    # here **heroname** is "Spider Man", "Peter Parker" etc. 
    # every ietration with sh.each { .. } your another variable **realname** 
    # is **nil** 
    sh.each do |heroname, realname| 
     puts "#{realname} is #{heroname}" 
     # as **realname** is always **nil**, you got the output as 
     # is Spider Man 
     # is Peter Parker 
     # ..... 
     # ..... 
    end 
end 
+1

你剛剛獲得了 「閃電俠」 的徽章:P大聲笑 – mdesantis

+1

這一工程!爲什麼我沒有想到這一點!知道它是一個二維數組,我滅絕告訴我可能使用.each方法兩次。 @ mdsantis:確實是「Flash」徽章。 – Jan

1

試試這個也

super_heroes.each do |sh| 
    puts sh.join(" is ") 
end