When I write methods that take an optional block, I typically use something like
block.call if block_given?
However, in method defined dynamically like the one below, block_given?
doesn't seem to work.
class Foo
%w[bar baz].each do |method_name|
define_singleton_method(method_name) do |&block|
puts "Was #{method_name} given a block? #{block_given?}"
puts block.call
end
end
end
Foo.bar { puts 'I am a block' }
The block is called as expected, but block_given?
returns false.
Why is this?