如何修改名称给定的变量的值
我希望有一个方法接受一个字符串,然后用该字符串的名称更新一个变量。这是我尝试的例子:就在上面的方法“送”之前如何修改名称给定的变量的值
syntax error, unexpected tIVAR
与指针:
@other_class = OtherClass.new()
def change_variable(variable_string)
[email protected]_class.send.variable_string += 1
end
我得到的错误。有没有人有任何建议,使这项工作?
立即syntatic错误是,你使用self
和@
错误。
任何一个都可以,但不能彼此结合。
所以在你的情况下self.other_class.send...
会很好,但你不能宣布它为@
。 和@
一样,但你不能做self
。
这些意在做不同的事,并且这些是
@
是实例变量,所以是self
但不同的是,使用直接@
到哪里self
调用该方法other_class
调用属性other_class
。
所以@
既是一个getter和setter所以你可以做
@other_class = my_milk_man
到哪里
self.other_class
->
self.other_class (as getter)
,
self.other_class = my_milk_man
- >self.other_class= (as setter)
。
谢谢 - 这是固定的。我刚才认为这个错误与我使用变量名的方式有关 - 我应该更信任Ruby! – Serenthia 2013-03-07 22:12:13
你可能想instance_variable_set http://ruby-doc.org/core-2.0/Object.html#method-i-instance_variable_set
使用变量的语法是我认为:
other_var = ('@' + variable_string).to_sym
@other_class.instance_variable_set(other_var, @other_class.instance_variable_get(other_var) + 1)
我不知道这种方法 - 谢谢你的信息 – Serenthia 2013-03-07 22:14:25
'varaible_string'代表一个实例变量吗? – sawa 2013-03-07 18:23:50
使用'self'或'@'不''self。@ ....' – 2013-03-07 18:24:00
不知道你想要什么,但删除'self' – enthrops 2013-03-07 18:24:20