能够在另一个变量的名称中使用一个变量吗? Ruby
Able to use a variable within another variable's name? Ruby
所以我的目标是能够 运行 通过 "while" 循环,并在每次迭代中创建一个新变量,在该变量名称中包含 "iteration count" 并将其存储稍后在循环外使用。详情见下文。
注意:代码在很多方面显然是错误的,但我这样写是为了让它更清楚?至于我想要完成的事情。感谢您就如何实现这一点提供任何意见。
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 中是否可以做到这一点。谢谢!
您可以使用 instance_variable_set
设置变量并以这种方式引用它
instance_variable_set("@player#{count}_roll", rand(20))
我认为最好的方法是使用数组或散列,数组是这样的:
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"]
所以我的目标是能够 运行 通过 "while" 循环,并在每次迭代中创建一个新变量,在该变量名称中包含 "iteration count" 并将其存储稍后在循环外使用。详情见下文。
注意:代码在很多方面显然是错误的,但我这样写是为了让它更清楚?至于我想要完成的事情。感谢您就如何实现这一点提供任何意见。
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 中是否可以做到这一点。谢谢!
您可以使用 instance_variable_set
设置变量并以这种方式引用它
instance_variable_set("@player#{count}_roll", rand(20))
我认为最好的方法是使用数组或散列,数组是这样的:
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"]