2013-07-23 46 views
2

這是最好的代碼解釋。鑑於這種類:循環使用實例變量,如何更改它們?

class Simple 
    def initialize 
    @a, @b, @c = 0.0, 0.0, 0.0 
    end 
    attr_accessor :a, :b, :c 
    def addOne() 
    for i in [@a, @b, @c] do 
     i += 1.0 
    end 
    end 
end 
s = Simple.new 
s.addOne() 
puts s.a 
# outputs 0.0 

我怎樣才能改變addOne()實際做出來嗎?(在加1到所有瓦爾for循環)

我猜測,實際上for i in ...包裝了[email protected]它創建於@a數量的新實例。但我看不出任何方法可以循環使用幾個實例變量並將其更改。請注意,我的真實課程顯然更復雜。所以,是的,我確實想循環變量。

回答

2

您的代碼不起作用,因爲表達i += 1.0增量不相關的實例變量的局部變量i的價值。爲了讓它工作,你可以做這樣的事情:

class Simple 
    # ... 
    def add_one 
    [:a, :b, :c].each { |v| send("#{v}=", send(v) + 1.0) } 
    end 
end 

s = Simple.new 
s.add_one 
puts s.a 
# => 1.0 
+1

sawa's是國際海事組織更直接的,但我喜歡這個答案,因爲它將對訪問者進行任何其他抽象(因爲OP已使訪問器可用)。 –

4
%i[@a @b @c] 
.each{|sym| instance_variable_set(sym, instance_variable_get(sym) + 1.0)} 
+0

非常快。 :-)我在數組前做了什麼? – Pascal

+0

http://stackoverflow.com/questions/17355177/what-is-the-origin-of-i-notation – sawa

+0

隨着紅寶石1.9.3這不是workking我。它報告@a的未知字符串類型。任何線索? – Pascal