0
0
RubyHow-ToBeginner · 3 min read

How to Use yield in Ruby: Simple Guide with Examples

In Ruby, yield is used inside a method to call a block passed to that method. It allows the method to pause and execute the block's code, then resume after the block finishes.
📐

Syntax

The yield keyword is placed inside a method to call the block given to that method. If the block takes arguments, you pass them to yield like a method call.

  • yield: Calls the block without arguments.
  • yield(arg1, arg2): Calls the block with arguments.
  • If no block is given, calling yield raises an error unless checked.
ruby
def method_name
  # some code
  yield
  # more code
end
💻

Example

This example shows a method that uses yield to run a block passed to it. The block receives a value from the method.

ruby
def greet
  puts "Hello"
  yield("friend")
  puts "Goodbye"
end

greet do |name|
  puts "Nice to meet you, #{name}!"
end
Output
Hello Nice to meet you, friend! Goodbye
⚠️

Common Pitfalls

Common mistakes when using yield include:

  • Calling yield without a block, which causes an error.
  • Not passing expected arguments to the block.
  • Confusing yield with explicit block parameters like &block.

To avoid errors, check if a block is given with block_given? before calling yield.

ruby
def safe_method
  if block_given?
    yield
  else
    puts "No block provided"
  end
end

safe_method
safe_method { puts "Block runs" }
Output
No block provided Block runs
📊

Quick Reference

KeywordDescription
yieldCalls the block passed to the method
yield(args)Calls the block with arguments
block_given?Returns true if a block is passed
&blockCaptures the block as a Proc object (alternative to yield)

Key Takeaways

Use yield inside a method to run the block passed to it.
Always check block_given? before calling yield to avoid errors.
You can pass arguments to the block by giving them to yield.
yield pauses the method, runs the block, then resumes after the block finishes.