Initializing dynamic instance methods

Hi list!

What’s the best way to remedy the error/warning that the following
code produces?

class Parent
def self.foo()
module_eval(“def foo(); @foo; end”)
module_eval(“def foo=(newfoo); @foo = newfoo; end”)
end
end

class Child < Parent
foo
end

c = Child.new
p c.foo

(running with ruby -w)
(eval):1: warning: instance variable @foo not initialized
nil

Sincerely

/lasso

Lars O. schrieb:

class Child < Parent
foo
end

c = Child.new
p c.foo

(running with ruby -w)
(eval):1: warning: instance variable @foo not initialized
nil

I don’t know if its the best way, but you could try

module_eval(“def foo(); @foo if defined? @foo; end”)

Regards,
Pit

On Feb 14, 7:31 am, “Lars O.” [email protected] wrote:

end
I dunno what your criteria is for ‘best’, but this fixes it:
module_eval(“def foo(); @foo ||= nil; end”)
(Though that runs over values of false with nil.)

Thanks, the worked flawlessly. I just added an else clause so that I
can have other default values than nil.

class Parent
def self.foo()
module_eval(“def foo(); if defined?(@foo) then @foo else nil
end; end”)
module_eval(“def foo=(newfoo); @foo = newfoo; end”)
end
end

class Child < Parent
foo
end

c = Child.new
p c.foo

/lasso

Phrogz wrote:

I dunno what your criteria is for ‘best’, but this fixes it:
module_eval(“def foo(); @foo ||= nil; end”)
(Though that runs over values of false with nil.)

That’s what I do also; just be careful however not to refer to the
instance variable from within the class; use the accessor method.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs