What if one simple word could make your methods magically run any code you want inside them?
Why Yield to execute blocks in Ruby? - Purpose & Use Cases
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.
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.
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.
def greet puts 'Hello' # manually add custom code here puts 'Goodbye' end
def greet puts 'Hello' yield if block_given? puts 'Goodbye' end
You can write one method that runs different code blocks, making your programs more flexible and reusable.
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.
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.