0
0
Rubyprogramming~3 mins

Why Yield to execute blocks in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if one simple word could make your methods magically run any code you want inside them?

The Scenario

Imagine you want to write a method that does some setup, then runs some custom code you write each time it's called. Without yield, you'd have to write many similar methods or pass around complicated code objects.

The Problem

Manually repeating code or passing explicit blocks everywhere is slow and error-prone. It makes your code bulky and hard to change. You lose the simple flow of running custom code inside a method.

The Solution

Using yield lets your method pause and run any block of code given to it. This keeps your method flexible and clean, letting you insert custom actions without rewriting the method.

Before vs After
Before
def greet
  puts 'Hello'
  # manually add custom code here
  puts 'Goodbye'
end
After
def greet
  puts 'Hello'
  yield if block_given?
  puts 'Goodbye'
end
What It Enables

You can write one method that runs different code blocks, making your programs more flexible and reusable.

Real Life Example

Think of a restaurant chef who prepares the main dish but lets the waiter add special sauces or toppings for each customer's order. yield is like letting the waiter add their special touch inside the chef's process.

Key Takeaways

Yield lets methods run custom code blocks passed to them.

This avoids repeating code and keeps methods flexible.

It makes your programs easier to read and maintain.