i'm trying access instance variable in methods of module.
module filter def self.included(target) puts "included: #{@var}" target.instance_variable_set(:@var, @var) # doesn't seem work end def self.var=(var) @var = var end def self.var @var end def hello @var end end f = filter f.var = "hello" puts "set: #{f.var}" class main include filter end m = main.new puts "hello: #{m.hello}" it produces output:
ruby test2.rb set: hello included: hello hello: the last line "hello:" needs output "hello: hello". how initialize @var instance variable make happen?
as many-many others, confused term "instance variable" here. it's instance variable, right, it's not instance think about.
remember, in ruby object. classes themselves.
def self.included(target) puts "included: #{@var}" target.instance_variable_set(:@var, @var) # doesn't seem work end so here you're setting instance variable on target (which class, likely). yet you're trying read instance of target.
m = main.new puts "hello: #{m.hello}" this variable is:
puts "the right hello: #{main.instance_variable_get(:@var)}" naturally, not possible set instance variable (in manner) on instance not yet exist! depending on you're after, different strategies can implemented. suggest ask another, more refined question.
Comments
Post a Comment