← Back to Ruby Course | Chapter 8: Blocks, Procs & Lambdas | Lesson 2 of 6

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.
Syntax
ruby
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)

markup
def each_pair
  yield(1, "one")
  yield(2, "two")
end

each_pair { |num, word| puts "#{num}: #{word}" }
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
  1. Yielding two values but the block takes one, |num|, so it only receives the first.
  2. Yielding values in a different order than the block expects, so num and word are swapped.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.