gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:34:25 24 4
gpt4 key购买 nike

我有这段代码:

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

经过几个小时的代码迭代,我还是想不通。如果有人能让我朝着正确的方向前进并解释我做错了什么,我将不胜感激。谢谢!

最佳答案

做如下:

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

关于ruby - 如何在 Ruby 中正确访问和迭代多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21836226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com