Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require a block in Ruby?

Tags:

Is there any built in way to require that a block be passed to a Ruby method? I realize I can just raise an exception if block_given? is false, but is there some nicer way to do it?

like image 635
Kyle Slattery Avatar asked Feb 22 '10 05:02

Kyle Slattery


1 Answers

Simply by using yield.

If you include yield in a method, and a block is not given, it throws an error.

Put this in a file and run it:

def needs_block     yield end  needs_block 

It will throw an error like this:

LocalJumpError: no block given     from (irb):14:in `needs_block'     from (irb):16 
like image 179
Doug Neiner Avatar answered Oct 11 '22 18:10

Doug Neiner