I know that I can dynamically define methods on a class using define_method
, and that I specify the parameters this method takes using the arity of the block.
I want to dynamically define a method that accepts both optional parameters and a block. In Ruby 1.9, this is easy because passing a block to a block is now allowed.
Unfortunately, Ruby 1.8 doesn't allow this, so the following won't work:
#Ruby 1.8
class X
define_method :foo do |bar, &baz|
puts bar
baz.call if block_given?
end
end
x = X.new
x.foo("foo") { puts "called!"} #=> LocalJumpError: no block given
Replacing the explicit block.call
with yield
doesn't fix the problem either.
Upgrading to Ruby 1.9 is unfortunately not an option for me. Is this an intractable problem, or is there a way around it?