2013-03-07 63 views
0

我希望有一个方法接受一个字符串,然后用该字符串的名称更新一个变量。这是我尝试的例子:就在上面的方法“送”​​之前如何修改名称给定的变量的值

syntax error, unexpected tIVAR

与指针:

@other_class = OtherClass.new() 

def change_variable(variable_string) 
    [email protected]_class.send.variable_string += 1 
end 

我得到的错误。有没有人有任何建议,使这项工作?

+0

'varaible_string'代表一个实例变量吗? – sawa 2013-03-07 18:23:50

+0

使用'self'或'@'不''self。@ ....' – 2013-03-07 18:24:00

+0

不知道你想要什么,但删除'self' – enthrops 2013-03-07 18:24:20

回答

1

立即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)

+0

谢谢 - 这是固定的。我刚才认为这个错误与我使用变量名的方式有关 - 我应该更信任Ruby! – Serenthia 2013-03-07 22:12:13