define_method with dynamic method name

M

Marcin Balinski

Hi
I want to define new method with dynamic name eg:

def method_name
"abrakadabra"
end

define_method(method_name.to_sym){puts "done."}

I cant do it this way, it causes: undefined local variable or method
`method_name'
Is there any other way to achieve this?
 
S

Stefano Crocco

Hi
I want to define new method with dynamic name eg:

def method_name
"abrakadabra"
end

define_method(method_name.to_sym){puts "done."}

I cant do it this way, it causes: undefined local variable or method
`method_name'
Is there any other way to achieve this?

Are you using define method directly in the class body or from within an
instance method? In the first case (and also if you're using it from a class
method), then you need to define method_name as a class method, not as an
instance method:

class C

def self.method_name
"abrakadabra"
end

define_method(method_name){puts "done."}

end

C.new.abrakadabra

By the way, you don't need to call to_sym, since define_method also accepts a
string as argument.

I hope this helps

Stefano
 

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
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top