The yield Keyword in Ruby
Overview
The word "yield" is frequently used in programming to describe a statement that gives control back to the caller while keeping the function's execution state intact. Many programming languages, including Ruby, employ the yielding technique. When a block is passed to a method in Ruby, it is executed using the yield keyword. The yield keyword can be used by a method to execute a block when it is called along with one.
Introduction to Ruby Yield Keyword
The Ruby yield keyword is an important tool that enables programmers to write adaptable and reusable code. Developers may create methods that users can modify with various bits of code by utilizing yield.
In Ruby, a block supplied to a method is executed using the yield keyword. There are three different sorts of yield statements that may be used in Ruby:
- Simple yield
- Yield with arguments
- Yield with return value
Let’s examine each yield statement type in more depth.
Simple Yield
The simplest type of yield statement in Ruby is the simple yield statement. A simple yield statement simply executes the block that is passed to the method. Here is an example of a method that uses a simple yield statement:
When this code is executed, this output will be produced:
In the above example, a block is passed along the method call. Inside the method, the statement before yield gets executed first. Then, the block of code that is passed gets executed due to the yield statement. Finally, the statement after the yield statement is executed.
Yield with Argument
The next type of yield statement in Ruby is yield with argument. To send an argument to the block that is performed by the yield statement, we can use the yield with argument syntax. An example that makes use of yield with the argument is shown here:
When this code is executed, this output will be produced:
In this example, the func method is defined to accept a block as an argument. The func method executes the block using the yield statement. Inside the block, the message "Inside block arg" is printed, where the value of "arg" is passed as the argument to the block.
Yield with Return Value
The final yield statement available in Ruby is the yield with a return value. It is utilized to pass an argument to the block executed by the yield statement, while also returning a value from that block. Here's an illustration of a method employing yield with return value:
When this code is executed, it will output the following:
In this case, the supplied block is given an argument by the function method. Based on this parameter, the block then returns a value. Finally, the method displays the returned value.
How does the Yield Keyword Work in Ruby?
The yield keyword in Ruby is a mechanism that allows a method to invoke a block of code. When a method is called with a block, the method can call the yield keyword to execute the block. The yield keyword is used within the method to transfer control to the associated block.
The execution briefly stops when the yield statement is reached, and control is then transferred to the block. Any inputs supplied to the yield statement are also passed to the block, which is then performed. If required, the block can execute its own logic and return values.
Once the block has finished running, the control moves back to the method, precisely to the line following the yield statement. The remaining code can then be executed by the method.
Yielding to a Block
Yielding to a block in Ruby involves using the yield keyword within a method to execute a block of code that was passed as an argument, allowing for dynamic behavior and re-usability. The yield statement transfers control to the block, and any arguments supplied to the yield statement are treated as parameters that can be accessed within the block.
What is a Block in Ruby?
In Ruby, block is a segment of code (method without a name) that can be passed as an extra argument to other methods.
Blocks in Ruby are highly flexible and powerful. They are commonly used alongside iterators, such as the each method, to perform operations on each element of a collection. They also enable the addition of extra functionality to existing methods or the creation of new control structures.
Blocks in Ruby can be declared using two syntaxes: the do...end syntax and the curly brace {...} syntax. While both syntaxes serve the same purpose, the do...end syntax is typically favored for multi-line blocks, whereas the curly brace syntax is commonly employed for single-line blocks.
Here's an illustration of a block:
How to Yield to a Block?
In Ruby, we must use the yield keyword within a method that takes a block to yield to it. When the yield keyword is used, the method executes the block that was supplied to it. Any arguments supplied to the yield statement are passed as parameters to the block.
Example:
Output:
The yield keyword is used by the func method in this example to execute the block that was supplied to it. The block completes its execution, and then the func method resumes the execution of the remaining statements.
Examples to Implement Yield in Ruby
Let's explore a few examples to see how the yield keyword can be used in Ruby.
Example - 1
Suppose we want to write a method that calculates the sum of a given array of numbers. We can use the yield keyword to customize the summation logic. Here's an example:
Explanation:
In this example, the func method iterates over each number in the given array. It calls the yield keyword with each number as an argument, and the block multiplies the number by itself. The result is then accumulated in the sum variable. Finally, the method returns the sum.
Example - 2
Suppose we have a method that formats a string and we want to allow users to customize the formatting. We can use the yield keyword to achieve this. Here's an example:
Output:
Explanation:
In this example, the yield keyword is called by the func method with the supplied string as an argument. This string is formatted in the block. After formatting, the string is returned that is then printed to the console.
Example - 3
We can make a Ruby method perform different tasks by changing the block of code passed each time.
The output of the above code is:
Explanation:
The func method is called four times in this example, each time with a different block of code. As a result, the same method executes different tasks in different contexts.
Conclusion
- The yield keyword in Ruby allows the execution of code blocks supplied to a method, allowing for flexibility and customization.
- There are three methods to utilize the yield keyword: simple yield, yield with argument, and yield with return value.
- Simple yield executes the block without passing any arguments.
- Yield with argument allows the method to pass an argument to the block for customization.
- Yield with return value returns a value from the block.
- Blocks in Ruby are chunks of code that can be passed to methods and executed within the context of the method.
- Blocks can take arguments and return values, but they are always associated with a specific method.
- Using the yield keyword, developers can write methods that can be customized by users with different blocks of code.
- Yielding to a block allows for the execution of the block within the method, enhancing the functionality and flexibility of the code.
- Examples demonstrated how the yield keyword can be used to implement custom summation logic and customize output formatting.
- The yield keyword in Ruby is thus a valuable tool for creating dynamic and adaptable code by enabling the execution of user-defined blocks within methods.