'Detect if block is given in Ruby define_method block

When searching, keywords 'block' and ruby 'define_method' keep telling me to explicitly define + call the block. Tried a bunch of stuff, including looking at source code but just can't tell. All I'd like to know is if there is some way to have a block_given? call be called in the context of the method. I.e.

define_method(:example) do
  raise TypeError if block_given?
  nil
end


Solution 1:[1]

block_given? seems to get confused in this case. You can try something like this instead -

 define_method(:hello) do |*args, &block|
    raise TypeError unless block
 end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joel Blum