Member-only story

The Power Of “Yield” in Ruby

FS Ndzomga
2 min readJan 19, 2023
Photo by Maxwell Nelson on Unsplash

The yield keyword in Ruby is used to call a block of code that has been passed to a method. It allows for the method to execute code that is defined outside of itself, making it a powerful tool for creating reusable and modular code.

One way to use yield is to pass a block of code to a method that will execute the block with the yield keyword. For example, the following code defines a method print_twice that takes a block and prints the result of the block twice:

This code will output “Hello, World!” twice.

Another way to use yield is to pass a block and also pass arguments to the block. For example, the following code defines a method greet that takes a name and a block, and yields the name to the block:

This code will output “Hello, John!”.

yield can also be used to return a value from a block. For example, the following code defines a method multiply_by that takes a number and a block and yields the number to the block to get the result of the multiplication:

In conclusion, the yield keyword in Ruby is a powerful tool for creating reusable and modular code by allowing a method to execute code that is defined outside of itself. It can be used to pass a block of code to a method, pass arguments to a block, or return a value from a block.

--

--

FS Ndzomga
FS Ndzomga

Written by FS Ndzomga

Engineer passionate about data science, startups, philosophy and French literature. Built lycee.ai, discute.co and rimbaud.ai . Open for consulting gigs

No responses yet