简体   繁体   中英

Able to use a variable within another variable's name? Ruby

So my goal is to be able to run through a "while" loop and in each iteration create a new variable that includes the "iteration count" within that variables name and stores it for later use outside of the loop. See below for more details.

NOTE: The code is clearly wrong in so many ways but I'm writing it this way to make it more clear? as to what I am trying to accomplish. Thanks for any input on how this is possible.

count = "4"
while count > "0"
  player"#{count}"_roll = rand(20)
  puts 'Player "#{count}" rolled: "#{player"#{count}"_roll}"'
  count -= 1
end

My goal is then to be able to access the variables that were created from within the loop at a later part of the program like so (more or less)

puts player4_roll
puts player3_roll
puts player2_roll
puts player1_roll

The key being that these variables were A) created in the loop B) With names relying on another variables input, and C) accessible outside the loop for later use.

Hopefully my question came out clear and any input will be greatly appreciated. I'm very new to programming and trying to get my head wrapped around some more complex ideas. I'm not sure if this is even possible to do in Ruby. Thanks!

I think the best way is to use arrays or hashes, with arrays its something like this:

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

You store the result in the array and then you loop trough it. If you want the result of the second iteration of the loop you do something like this:

puts array[1]

If you want to use Hashes there are some modifications you need to do:

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

If you want the result of the second iteration of the loop you do something like this:

puts hash["player1_roll"]

您可以使用instance_variable_set设置变量并以这种方式引用

  instance_variable_set("@player#{count}_roll", rand(20))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM