yield
yield is how a method runs the block that was handed to it, like a chef pausing to run the special step you gave. The method decides when the block gets its turn.
In this page:
Syntax
def method_name
yield
end
method_name { # block body }
yield
Inside a method, yield invokes the block that was passed to it, optionally passing values into the block as arguments.
block_given? checks whether a block was actually supplied before yielding, avoiding an error if a caller forgets to pass one. This is the mechanism that lets you write your own methods that behave like each or map.
Note:
Always guard yield with
if block_given? unless a block is strictly required, to avoid a LocalJumpError when none is passed.Example: yield
def repeat_twice
yield
yield
end
repeat_twice { puts "Hello!" }
def with_value
if block_given?
yield(42)
else
puts "No block given"
end
end
with_value { |n| puts "Got: #{n}" }
with_value
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Calling
yieldwhen no block was given, which raisesLocalJumpError; guard withblock_given?. - Passing arguments to
yieldthat the block does not accept, and expecting an error, when extra values are ignored. - Writing
yieldinside a method and forgetting the block on the call, so nothing happens.
Chapter Summary
- Methods are defined with parameters, default parameters, and return values.
- The splat operator (
*args) and keyword arguments (**kwargs) accept flexible inputs. - Blocks and
yieldlet a method run code passed to it.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: