Adding methods at runtime

One of the things that seems to draw people to Ruby is the ability to create and change all things at metprogrammatically at runtime. This in turn allows users to create things like domain-specific languages and the like.

I’m possibly overusing these features at the moment, because it’s a cool new thing ™.

So, let’s see how to add methods at runtime. Since this is Ruby, there are multiple ways to do this, making things more confusing.

(See also the follow-up article)

2 thoughts on “Adding methods at runtime

  1. “however, I suppose you can’t pass multiple parameters.”

    Sorry, this is not true. You pass a block to define_method and blocks can have any number of params:

    $ irb
    >> class Test
    >> define_method(“foo”) do |param1, param2|
    ?> print “foo #{param1} #{param2}”
    >> end
    >> end
    => #<Proc:0xf777a1a8@(irb):2>
    >> t = Test.new
    => #<Test:0xf7777fac>
    >> t.foo
    ArgumentError: wrong number of arguments (0 for 2)
    from (irb):7:in `foo’
    from (irb):7
    >> t.foo(1,2)
    foo 1 2=> nil

  2. Ah, yes. What I had read somewhere (but not tried out) and wanted to say, that you can pass multiple parameters in the form of “def method(*params)”

    However, this isn’t quite true either. If you only declare one block parameter, but pass multiple parameters to the method, you will have an array as the block parameter.

    This will cause a Ruby warning (“multiple values for a block parameter”), however.

Comments are closed.