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

yield

In this page:

  1. yield

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
🔒

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.