【问题标题】:Able to use a variable within another variable's name? Ruby能够在另一个变量的名称中使用一个变量吗?红宝石
【发布时间】:2015-01-16 23:17:30
【问题描述】:

所以我的目标是能够运行“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 中实现。谢谢!

【问题讨论】:

  • 这是为了调试目的吗?
  • @Anthony 我对编程很陌生,以至于我什至不确定什么是调试,但代码是我正在制作的虚拟代码,以找到稍后实现的答案我正在制作的德州扑克风格游戏。基本上这部分代码用于计算玩家发了哪些牌,然后创建一个变量“player_x_hand”来保存牌的字符串值(其中 x = 迭代中的计数)如果这一切都有意义.. ..
  • 我很确定这个问题可以通过其他方式解决。有一些元编程方法可以创建变量,但我怀疑它在这种情况下是否有用。为什么不直接将卷作为 DATA 存储在一个数组中呢?
  • @daremkd 是的,我最近开始尝试找到一种方法来使用哈希来存储卡值,但由于这是我最初的想法,我想在放弃它之前检查它是否可能用于另一个概念.不过感谢您的输入:)

标签: ruby variables syntax


【解决方案1】:

我认为最好的方法是使用数组或哈希,数组是这样的:

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"]

【讨论】:

  • 我认为散列的想法肯定更适合我的目的,尽管放入您的代码并运行它返回 14: syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '(' puts hash{"player1_roll"}14: syntax error, unexpected $end, expecting keyword_end puts hash{"player1_roll"} ^ 我认为总的来说,如果我能清除错误,这应该工作得很好。谢谢!
  • 忘记错误。将“如果你想要循环的第二次迭代的结果,你可以这样做:”复制到代码中是我的错。奇迹般有效。再次感谢!
【解决方案2】:

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

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

【讨论】:

  • Running that puts: Player "#{count}" rolled: "@player#{count}_roll" Player "#{count}" rolled: "@player#{count}_roll" Player "#{count}" rolled: "@player#{count}_roll" Player "#{count}" rolled: "@player#{count}_roll" 我需要:Player 4 rolled: 15 Player 3 rolled: 20 Player 2 rolled: 2 Player 1 rolled: 12 抱歉我没听说过 instance_variable之前,也许有点困惑?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 2017-04-01
  • 2021-08-22
  • 2010-09-28
  • 2011-07-23
  • 1970-01-01
  • 2014-01-12
相关资源
最近更新 更多