Dynamic method creation

M

Matt

Hi! Is there a way to create a regular expression type method and pull
the pieces from that? I can find how to add methods dynamically but
what I really need is something like this.

def <name>_requires id
self.requires name, id
end


def requires name, id
...
end

so i could type something like test_requires 4 and it would transmit the
parameters test and 4 to the requires method.

thanks!

Matt
 
C

Chris Carter

Hi! Is there a way to create a regular expression type method and pull
the pieces from that? I can find how to add methods dynamically but
what I really need is something like this.

def <name>_requires id
self.requires name, id
end


def requires name, id
...
end

so i could type something like test_requires 4 and it would transmit the
parameters test and 4 to the requires method.

thanks!

Matt

The following (untested) code should work.

def method_missing sym,*args,&block
sym = sym.to_s
if sym =~ /(\w+)_requires/ && args.size == 1
requires $1, *args
end
end
 
M

Matt Sir

Chris said:
The following (untested) code should work.

def method_missing sym,*args,&block
sym = sym.to_s
if sym =~ /(\w+)_requires/ && args.size == 1
requires $1, *args
end
end


Thank you so much! Worked perfectly!
 

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,775
Messages
2,569,601
Members
45,183
Latest member
BettinaPol

Latest Threads

Top