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?
Asked
Active
Viewed 4,682 times
24

niton
- 8,771
- 21
- 32
- 52

Kyle Slattery
- 33,318
- 9
- 32
- 36
3 Answers
28
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

Doug Neiner
- 65,509
- 13
- 109
- 118
-
1Well that was way too easy :) Thanks! – Kyle Slattery Feb 22 '10 at 05:18
17
raise 'need block' unless block_given?

Baldrick
- 23,882
- 6
- 74
- 79

rogerdpack
- 62,887
- 36
- 269
- 388
-
2This is the best answer, since it has no side effects (i.e. calling the block). – Per Lundberg Jul 07 '16 at 10:03
1
If your method required a block, Ruby will prompt it. The raise keyword doesn't require a block, it only prompts a message for handling an Exception.
It could be a method like the above example
def needs_block
yield
end
needs_block
Or you could require a Proc
def needs_block(&Proc)
proc.call
end
Anyway, adding raise block_given? would be nice.
"The raise method is from the Kernel module. By default, raise creates an exception of the RuntimeError class. To raise an exception of a specific class, you can pass in the class name as an argument to raise".