不确定这个模式是什么,但这里是场景:
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)
这种模式被称为"爱抚"; 如果您要计算这样的密钥,那么显式使用哈希或数组可能是一个更好的主意.
| 归档时间: |
|
| 查看次数: |
3654 次 |
| 最近记录: |