因此,我的目标是能够运行“ while”循环,并在每次迭代中创建一个新变量,该新变量在该变量名称中包含“迭代次数”,并将其存储以供以后在循环外部使用。请参阅下面的更多细节。
注意:代码在很多方面显然是错误的,但是我以这种方式编写它是为了使其更清楚?关于我要完成的工作。感谢您提供有关如何实现此目标的任何意见。
count = "4"
while count > "0"
player"#{count}"_roll = rand(20)
puts 'Player "#{count}" rolled: "#{player"#{count}"_roll}"'
count -= 1
end
然后,我的目标是能够像这样(或多或少)访问在程序的后面部分从循环内部创建的变量。
puts player4_roll
puts player3_roll
puts player2_roll
puts player1_roll
关键是这些变量是A)在循环中创建的B)名称依赖于另一个变量输入的输入,以及C)可在循环外部访问以供以后使用。
希望我的问题清楚地提出,任何意见将不胜感激。我对编程非常陌生,并试图将自己的想法缠在一些更复杂的想法上。我不确定在Ruby中是否还可以做到这一点。谢谢!
我认为最好的方法是使用数组或哈希,而数组则如下所示:
count = 0
array = []
while count < 4 do
array[count] = rand(20)
puts "Player #{count} rolled: #{array[count]}"
count += 1
end
array.each do |var|
puts var
end
您将结果存储在数组中,然后循环通过它。如果想要循环的第二次迭代的结果,请执行以下操作:
puts array[1]
如果要使用哈希,则需要做一些修改:
count = 0
hash = {}
while count < 4 do
hash["player#{count}_roll"] = rand(20)
puts "Player #{count} rolled: #{hash["player#{count}_roll"]}"
count += 1
end
hash.each do |key, var|
puts var
end
如果想要循环的第二次迭代的结果,请执行以下操作:
puts hash["player1_roll"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句