Can someone explain why the last yielder throws a no block given?
class Foo
def yielder
yield "hello"
end
end
class Mod
def initialize
@@foo = Foo.new
end
def self.foo
@@foo
end
end
worker = Mod.new
Mod.foo.yielder do |hello|
puts hello
end
Mod.foo.class.send(:define_method,:yielder) do
yield "new hello"
end
Mod.foo.yielder do |hello|
puts hello
end
Gives:
hello
test.rb:27:in `block in ‘: no block given (yield) (LocalJumpError)
from test.rb:30:in `’
A short introduction:
You don’t need the Mod-instance, if you define @@foo outside
initialize.You don’t need the Mod class to get the problem:
You may shorten your example again:
This is the same as:
End of Introduction.
And now, I’m not sure if I understood correct what you want (and if I understand ruby correct 😉 )
define_methodaccepts a block and use it as method body.If the new method should receive a block on its own, you must define it in the interface of the definition and call it:
Or the same logic in your example:
To make the code more robust, I would recommend some checks with
block_given?.