2013-03-07 62 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