Ruby:是否可以设置实例变量的值,其中实例变量通过字符串命名?

Zab*_*bba 7 ruby

不确定这个模式是什么,但这里是场景:

class Some
   #this class has instance variables called @thing_1, @thing_2 etc.
end
Run Code Online (Sandbox Code Playgroud)

有没有办法设置实例变量的值,其中实例变量名由字符串创建?

就像是:

i=2
some.('thing_'+i) = 55 #sets the value of some.thing_2 to 55
Run Code Online (Sandbox Code Playgroud)

Jos*_*Lee 17

Object上搜索"instance_variable" :

some.instance_variable_get(("@thing_%d" % 2).to_sym)
some.instance_variable_set(:@thing_2, 55)
Run Code Online (Sandbox Code Playgroud)

这种模式被称为"爱抚"; 如果您要计算这样的密钥,那么显式使用哈希或数组可能是一个更好的主意.