Member-only story
The Power Of “Yield” in Ruby
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.