0
0
Rubyprogramming~5 mins

Yield to execute blocks in Ruby

Choose your learning style9 modes available
Introduction

Yield lets a method pause and run a block of code given to it. This helps make methods more flexible and reusable.

When you want a method to run some custom code given by the user.
When you want to repeat a task but allow small changes each time.
When you want to separate the main work from small details.
When you want to write cleaner code without passing many parameters.
When you want to create your own iterator or callback.
Syntax
Ruby
def method_name
  # some code
  yield
  # more code
end

The yield keyword runs the block passed to the method.

If no block is given, calling yield causes an error unless you check with block_given?.

Examples
This method says hello, runs the block, then says goodbye.
Ruby
def greet
  puts "Hello"
  yield
  puts "Goodbye"
end

greet { puts "Nice to meet you!" }
The method yields twice, sending different words to the block each time.
Ruby
def repeat
  yield("Ruby")
  yield("Blocks")
end

repeat { |word| puts "I love #{word}!" }
This method checks if a block exists before yielding to avoid errors.
Ruby
def safe_yield
  if block_given?
    yield
  else
    puts "No block given"
  end
end

safe_yield
safe_yield { puts "Block here!" }
Sample Program

This program shows a method that yields two spices to a block, which then prints a message using them.

Ruby
def cooking
  puts "Start cooking"
  yield("salt", "pepper")
  puts "Done cooking"
end

cooking do |spice1, spice2|
  puts "Add #{spice1} and #{spice2} to the dish"
end
OutputSuccess
Important Notes

Use block_given? to check if a block was passed before calling yield.

You can pass values to the block by giving arguments to yield.

Blocks make your methods more flexible and let users add custom behavior.

Summary

Yield runs the block given to a method.

You can pass data to the block using yield with arguments.

Always check for a block with block_given? to avoid errors.