Ruby:是否可以设置实例变量的值,其中实例变量通过字符串命名?
发布时间:2020-12-17 04:26:42 所属栏目:百科 来源:网络整理
导读:不确定这个模式是什么,但这里是场景: class Some #this class has instance variables called @thing_1,@thing_2 etc.end 有没有办法设置实例变量的值,其中实例变量名由字符串创建? 就像是: i=2some.('thing_'+i) = 55 #sets the value of some.thing_2 t
不确定这个模式是什么,但这里是场景:
class Some #this class has instance variables called @thing_1,@thing_2 etc. end 有没有办法设置实例变量的值,其中实例变量名由字符串创建? 就像是: i=2 some.('thing_'+i) = 55 #sets the value of some.thing_2 to 55 解决方法
在
Object上搜索“instance_variable”:
some.instance_variable_get(("@thing_%d" % 2).to_sym) some.instance_variable_set(:@thing_2,55) 这种模式被称为“爱抚”;如果您要计算这样的密钥,那么明确使用Hash或Array可能是一个更好的主意. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |