Adding methods at runtime

Adding methods at runtime

Tags: , ,

2 Comments Leave yours

  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.

Leave a Reply