類方法(模塊內部)如何更新實例變量?考慮下面的代碼:一個類方法(模塊內部)如何更新一個實例變量?
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
你爲什麼想這樣做?根據定義,實例變量只有在有類的實例時纔有意義。目前你的'update_instance_variable'調用只會在類定義時執行一次。你是否試圖安排一些實例變量具有默認值? – mikej 2010-08-03 19:12:10
mikej是對的,你在做什麼是錯誤的。 – horseyguy 2010-08-04 00:18:50
我知道,當代碼update_instance_variable被執行時,沒有實例需要更新(只有類的實例)。好。但是必須是一種動態設置類的默認值的方法。我可以使用define_method來定義初始化,並在裏面定義實例變量的默認值,但我只想知道是否有不同的方式做... – Portela 2010-08-04 04:10:51