如何在Ruby中正确访问和迭代多维数组?

时间:2014-02-17 18:04:51

标签: ruby arrays multidimensional-array

我有这段代码:

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

经过几个小时的代码迭代,我仍然无法弄明白。如果有人能让我朝着正确的方向前进并解释我做错了什么,我将不胜感激。谢谢!

2 个答案:

答案 0 :(得分: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 :(得分:1)

也试试这个,

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