← Back to Ruby Course | Chapter 7: Methods | Lesson 7 of 7

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:

  1. yield
Syntax
ruby
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

markup
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
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. Calling yield when no block was given, which raises LocalJumpError; guard with block_given?.
  2. Passing arguments to yield that the block does not accept, and expecting an error, when extra values are ignored.
  3. Writing yield inside 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 yield let a method run code passed to it.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.