gpt4 book ai didi

ruby - 如何在 Ruby 中循环嵌套数组

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:31 25 4
gpt4 key购买 nike

对 Ruby 和一般编码非常陌生。我正在尝试遍历二维数组,但无法弄清楚。这是我拥有的:

--使用循环在不同的行上打印出每个人及其另一个 self 。

--布鲁斯·韦恩,又名 bat 侠

people = [
["Bruce", "Wayne", "Batman"],
["Selina", "Kyle", "Catwoman"],
["Barbara", "Gordon", "Oracle"],
["Terry", "McGinnis", "Batman Beyond"]
]

index = people[0][0]

first_name = people[0][0]
last_name = people[0][1]
hero_name = people[0][2]

4.times do
puts first_name + " " + last_name + "," " " + "a.k.a" " " + hero_name
index = index + 1
end

它确实打印了第一行但随后引发错误:

Bruce Wayne, a.k.a Batman
# `+': no implicit conversion of Integer into String (TypeError)

最佳答案

在 ruby​​ 中,我们不使用索引循环,例如 for 和 family;相反,我们迭代集合:

people =
[["Bruce", "Wayne", "Batman"],
["Selina", "Kyle", "Catwoman"],
["Barbara", "Gordon", "Oracle"],
["Terry", "McGinnis", "Batman Beyond"]]

people.each do |first, last, nick|
puts "#{first} #{last}, a.k.a #{nick}"
end

people.each do |first_last_nick|
*first_last, nick = first_last_nick
puts [first_last.join(' '), nick].join(', a.k.a ')
end

关于ruby - 如何在 Ruby 中循环嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50626251/

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