2010-08-03 66 views
0

類方法(模塊內部)如何更新實例變量?考慮下面的代碼:一個類方法(模塊內部)如何更新一個實例變量?

module Test 

    def self.included(klass) 
    klass.extend ClassMethods 
    end 

    module ClassMethods 

    def update_instance_variable 
    @temp = "It won't work, bc we are calling this on the class, not on the instance." 
    puts "How can I update the instance variable from here??" 
    end 

    end 

end 


class MyClass 
    include Test 
    attr_accessor :temp 
    update_instance_variable 

end 

m = MyClass.new # => How can I update the instance variable from here?? 
puts m.temp  # => nil 
+2

你爲什麼想這樣做?根據定義,實例變量只有在有類的實例時纔有意義。目前你的'update_instance_variable'調用只會在類定義時執行一次。你是否試圖安排一些實例變量具有默認值? – mikej 2010-08-03 19:12:10

+0

mikej是對的,你在做什麼是錯誤的。 – horseyguy 2010-08-04 00:18:50

+0

我知道,當代碼update_instance_variable被執行時,沒有實例需要更新(只有類的實例)。好。但是必須是一種動態設置類的默認值的方法。我可以使用define_method來定義初始化,並在裏面定義實例變量的默認值,但我只想知道是否有不同的方式做... – Portela 2010-08-04 04:10:51

回答

2

您必須將對象實例作爲參數傳遞給類方法,然後從方法返回更新的對象。

0

這沒有什麼意義。 您可以使用initialize方法來設置默認值。

class MyClass 
    attr_accessor :temp 

    def initialize 
    @temp = "initial value" 
    end 

end 

創建新對象時會自動爲您運行initialize方法。 當你的類聲明運行時,這個類還沒有,也不能是任何類。

如果你想以後能夠更改默認值,你可以做這樣的事情:

class MyClass 
    attr_accessor :temp 

    @@default_temp = "initial value" 

    def initialize 
    @temp = @@default_temp 
    end 

    def self.update_temp_default value 
    @@default_temp = value 
    end 

end 

a = MyClass.new 
puts a.temp 
MyClass.update_temp_default "hej" 
b = MyClass.new 
puts b.temp 

打印

initial value 
hej 

如果你也想,要想改變已經創建的實例變量你需要額外的魔法。請解釋你想要完成的事情。你可能做錯了:)

相關問題