How to create dinamicly method

D

Damjan Rems

What I am trying to accomplist is:

class MyClass
def addVar(var, val)
instance_variable_set("@#{var}", val)
define_method("#{var}") { || instance_variable_get("#{var}") }
end
end

c = MyClass.new
c.addVar('aa',10) # here pops the error
c.aa # should return 10

But I get this error:
NoMethodError: undefined method `define_method' for #<MyClass:0x2d01cc0
@aa=10>
from (irb):4:in `addVar'
from (irb):8

I know this should work because it's used all over rails.

Advice me please

TheR
 
M

Marcin Raczkowski

What I am trying to accomplist is:

class MyClass
def addVar(var, val)
instance_variable_set("@#{var}", val)
define_method("#{var}") { || instance_variable_get("#{var}") }
end
end

c = MyClass.new
c.addVar('aa',10) # here pops the error
c.aa # should return 10

But I get this error:
NoMethodError: undefined method `define_method' for #<MyClass:0x2d01cc0
@aa=10>
from (irb):4:in `addVar'
from (irb):8

I know this should work because it's used all over rails.

Advice me please

TheR
define_method won't work in instance method, you have to use class method o
just use eval("def #{var}; here return value; end");
 
D

Damjan Rems

Marcin said:
define_method won't work in instance method, you have to use class
method o
just use eval("def #{var}; here return value; end");

Yep: Each of these two variants work:
eval "def #{var};instance_variable_get('@#{var}');end"
eval("def #{var}; @#{var}; end")

I was trying this too, but forgot to add @ to variable name.


Thanks

TheR
 
B

Brian Candler

What I am trying to accomplist is:

class MyClass
def addVar(var, val)
instance_variable_set("@#{var}", val)
define_method("#{var}") { || instance_variable_get("#{var}") }

self.class.class_eval {
define_method("#{var}") { || instance_variable_get("@#{var}") }
}
end
end

c = MyClass.new
c.addVar('aa',10) # here pops the error
c.aa # should return 10

Regards,

Brian.
 

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

Forum statistics

Threads
474,237
Messages
2,571,189
Members
47,827
Latest member
wyton

Latest Threads

Top