【问题标题】:How do I correctly access and iterate over multidimensional arrays in Ruby?如何在 Ruby 中正确访问和迭代多维数组?
【发布时间】:2014-02-17 18:04:51
【问题描述】:

我有这段代码:

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

在迭代代码数小时后,我仍然无法弄清楚。如果有人能把我引向正确的方向并解释我做错了什么,我将不胜感激。谢谢!

【问题讨论】:

    标签: ruby arrays multidimensional-array


    【解决方案1】:

    如下操作:

    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
    

    【讨论】:

    • 行得通!我怎么没想到!!!知道这是一个二维数组,我的灭绝告诉我可能使用 .each 方法两次。 @mdsantis:确实是“Flash”徽章。
    【解决方案2】:

    也试试这个,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2014-01-13
      相关资源
      最近更新 更多