This works with Ruby 1.8.7, but not 1.8.6:
class X define_method(:foo) do |bar, &baz| puts bar baz.call if baz end end
Testing with:
X.new.foo("No block") X.new.foo("With block") { puts " In the block!"} p = proc {puts " In the proc!"} X.new.foo("With proc", &p)
gives:
No block With block In the block! With proc In the proc!
(since 1.8.6 it gives syntax error, unexpected tAMPER, expecting '|' .)
If you need additional arguments, as well as a block, you can try something like this:
class X define_method(:foo) do |*args, &baz| if args[0] bar = args[0] else bar = "default" end puts bar baz.call if baz end end
testing with:
X.new.foo X.new.foo { puts " No arg but block"}
gives:
default default No arg but block
matt
source share