Forum: Ruby Dynamic method creation

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F04efaee460b2ace5575870a4632287d?d=identicon&s=25 Matt (Guest)
on 2007-06-22 05:29
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
96931bfe0c2948f47a98e15ae52e5637?d=identicon&s=25 Chris Carter (cdcarter)
on 2007-06-22 05:43
(Received via mailing list)
On 6/21/07, Matt <wilsom8@rpi.edu> wrote:
>   ...
> Posted via http://www.ruby-forum.com/.
>
>

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
F04efaee460b2ace5575870a4632287d?d=identicon&s=25 Matt Sir (daicoden)
on 2007-06-22 06:11
Chris Carter wrote:
> On 6/21/07, Matt <wilsom8@rpi.edu> wrote:
>>   ...
>> Posted via http://www.ruby-forum.com/.
>>
>>
>
> 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!
This topic is locked and can not be replied to.