所以我试图创建动态变量,然后再使用它们而不必输入全名。我制作的测试代码如下
players = [1, 2, 3, 4]
players.each |player|
instance_variable_set("@player_#{player}_hand", "foo")
instance_variable_set("@player_#{player}_value", "bar")
}
puts @player_1_hand # => foo
puts @player_3_value # => bar
players.each { |player|
puts "@player_#{player}_hand"
}
# => @player_1_hand
# => @player_2_hand
# => @player_3_hand
# => @player_4_hand
我想动态调用和/或更新这些变量,但在初始化之后我不知道该怎么做。我发现的文档更令人困惑而不是有用。有人可以解释如何正确使用这些吗?
答案 0 :(得分:8)
我建议您按照OOP概念创建一个Player对象而不是许多实例变量,每个属性一个。所以,而不是
@player_1_hand
@player_3_value
尝试使用Player
类
class Player
attr_accessor :number, :hand, :value
def initialize(number)
@number = number
end
end
然后
p1 = Player.new(1)
p2 = Player.new(2)
p3 = Player.new(3)
p4 = Player.new(4)
[p1,p2,p3,p4].each do |player|
player.hand = ...
player.value = ...
end
p1.hand #=> ...
p1.value #=> ...
答案 1 :(得分:2)
我想警告你,我要给你的答案将适用于你想要完成的任务,但是你的方式类似于你需要锤子时使用扳手。当然,扳手可能会起作用,但我会解雇任何没有使用合适工具的水管工。
players.each { |p| puts instance_variable_get("@player_#{p}_hand") }
有关instance_variable_get
的更多信息,请访问apidock。
一般情况下,除非是creating instances of a class,否则应远离实例变量。但是对于像这样的脚本,坚持使用普通变量并远离实例变量。
答案 2 :(得分:2)
players = [1, 2, 3, 4]
players.each { |player|
instance_variable_set("@player_#{player}_hand", "foo")
instance_variable_set("@player_#{player}_value", "bar")
}
要调用您的变量,请使用eval
players.each { |player|
puts instance_variable_get("@player_#{player}_hand")
puts instance_variable_get("@player_#{player}_value")
}
要更新变量,请再次使用instance_variable_set
players.each { |player|
instance_variable_set("@player_#{player}_hand", instance_variable_get("@player_#{player}_hand") + (player + 5).to_s)
puts instance_variable_get("@player_#{player}_hand")
}
所有打印:
foo
bar
foo
bar
foo
bar
foo
bar
foo6
foo7
foo8
foo9
答案 3 :(得分:1)
当你想要每个属性的attr_accessor时,一个Struct而不是一个类会自动为你创建它们。
Player = Struct.new(:number, :hand, :value)
players = Array.new
(1..4).each do |i|
player = Player.new(i)
player.hand = 'something'
player.value = 'blah'
players.push player
end
players.each do |player|
puts "Player #{player.number} has hand #{player.hand} with value #{player.value}"
end
输出:
Player 1 has hand something with value blah
Player 2 has hand something with value blah
Player 3 has hand something with value blah
Player 4 has hand something with value blah