Initializing dynamic instance methods

L

Lars Olsson

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
 
P

Pit Capitain

Lars said:
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

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

module_eval("def foo(); @foo if defined? @foo; end")

Regards,
Pit
 
P

Phrogz

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

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.)
 
L

Lars Olsson

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
 
C

Clifford Heath

Phrogz said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top