yield with Arguments (Review)
yield can hand values to the block, which uses them as inputs, like passing an ingredient to a helper. This review shows how the method and block talk.
In this page:
Syntax
def method_name
yield value1, value2
end
method_name { |a, b| expression }
yield with Arguments (Review)
A block can receive arguments from yield value just like a method call, letting the method feed data into the block's logic. This is exactly how methods like each pass the current element into your block.
Multiple values can be yielded at once, matching multiple block parameters.
Note:
The number of values yielded doesn't have to exactly match the block's parameter count -- extra block parameters simply become nil.
Example: yield with Arguments (Review)
def each_pair
yield(1, "one")
yield(2, "two")
end
each_pair { |num, word| puts "#{num}: #{word}" }
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
- Yielding two values but the block takes one,
|num|, so it only receives the first. - Yielding values in a different order than the block expects, so
numandwordare swapped. - Expecting an error when the block has too many parameters, when the extras are
nil.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: