Yield in Ruby and How to use it
Published on 2022-02-10
Often, we like to run a regular expression within a method, numerous times without repeating the exact phrase. With the yield keyword, we can achieve the same result. The yield keyword can also supply inputs and generate the values. Let’s look at what “yield” in ruby is and how it is used.
What is yield in Ruby?
Ruby is an interpreted high-level programming language that can be used in various ways. It was designed by keeping the efficiency in programming and ease of use in mind.
When used with a block, the yield keyword allows you to provide a set of additional instructions during a method call. This technology enables you to tailor a procedure to your individual requirements. The yield statement in Ruby invokes any function using block code.
The key benefit of using yield in Ruby is that if we have a case where we want our method to do multiple tasks depending on the calling block, we can write some logic inside the block, and it will be executed when the method is called. To understand the significance of the yield keyword, we must first understand the concept of blocks.
A Block is a portion of code enclosed by do/end or curly brackets and is invoked using the yield keyword. The yield keyword instructs the method to stop running the code in this method and execute the code in this block. After that, the compiler is returned to the method’s code.
How does the yield keyword work?
With the following statements, we can understand how Ruby’s yield works:
-
Yield is a Ruby keyword that may be used to call any block in the program. It’s assumed that when we use the yield keyword in a method, we’re making a blocking call.
-
The number of parameters yield statements can pass to the block is limitless.
-
It will make as many attempts to call block as the number of times yield is provided in the function.
-
We may use | | as the argument’s name within the block to transmit any argument from yield to the block.
-
If the value of |number| is set to “Your message,” and the yield value is set to 5. Therefore, the |number| will have a value of 5.
Syntax
The yield statement has a simple syntax, as shown below.
yield `(' [expr [`,' expr...]])
yield [expr [`,' expr...]]
If no argument is specified, nil is utilized as an argument to evaluate the block sent to the current method. The block parameter’s argument assignment is done the same way as multiple assignments. The exception is thrown in the current procedure if no block is given.
How to use yield in Ruby?
Our method can receive a block and be called several times. A proc/lambda command might perform the same functionality; however, yield is way easier and quicker. When utilizing the yield keyword with a block, you can provide a set of additional instructions during the method’s invocation. When a method uses yield, it must be followed by a block. A block is just a section of code that we can use yield to inject into a function at any moment.
Let’s understand the usage of yield in Ruby with a few examples:
Example #1
Consider the code, shown below, where we declare a normal yield keyword twice inside a method and then call it.
def tuts
puts "In the tuts method"
#using yield keyword
yield
puts "Again back to the tuts method"
yield
end
tuts {puts "Yield executed!"}
Yield executed!
Again back to the tuts method
Yield executed!
Example #2
There is a method named yieldExample
in the code shown below, and there are several puts
statements and a yield statement inside it. When invoking the yieldExample function without giving any arguments, it will immediately produce the output as method contents. Moreover, it will call and print the method’s contents the first time, and then it will print the used block code when calling the method for the second time.
A method is defined, and yield statements are written inside it. These yield statements include messages as arguments, printed upon method call.
def yieldExample
puts "Here, you are in the method"
yield
puts "Again you fall below method block"
yield
end
yieldExample {puts "Here is the block of the code"}
Here, you are in the method
Here is the block of the code
Again you fall below method block
Here is the block of the code
Example #3
The same method, yieldExample
, is used in the code below, and several puts
statements and the yield statement are used in it. This is a whole different example because an argument to yield is supplied in this case. Numerous arithmetic operations may be conducted with a single procedure by employing this approach. When the arithmetic method is called from the block, the yield method reads data given by the block’s || operators.
A method is defined, and inside the method, yield is written as the method, which has two parameters.
def arithmetic(a, b)
yield(a, b)
end
puts "The summation of the two num variables is #{arithmetic(6, 4) { |a, b| a + b }}"
puts "The product of the two num variables is #{arithmetic(6, 4) { |a, b| a * b }}"
puts "The subtraction of the two num variables is #{arithmetic(6, 4) { |a, b| a - b }}"
puts "The division of the two num variables is #{arithmetic(6, 4) { |a, b| a / b }}"
The summation of the two num variables is 10
The product of the two num variables is 24
The subtraction of the two num variables is 2
The division of the two num variables is 1
Example #4
A method named yieldExample
is constructed in the example below, and several puts
and yield statements are placed inside it. When invoking the yieldExample method without supplying any arguments, the method with the number as an argument and printing the number is called. When the yieldExample method is run, it will display the output written inside the method calling block, and the yield statements will be used to read the number variable of the block.
A method is defined, and within the method, yield statements are written, each of which has an integer value as a parameter that will be printed when the method is called.
def yieldExample
yield 5
puts "Hey, we are now in the yieldExample method"
yield 100
end
yieldExample {|i| puts "Iteration number is #{i}"}
Iteration number is 5
Hey, we are now in the yieldExample method
Iteration number is 100
Example #5
In the example below, a method named yieldExample is constructed, and several ‘puts’ and yield statements are typed inside it. When using the yield method without a block of the message, the method with the parameter as the names of certain users and printing the names are called. When the yieldExample method is invoked, the output produced inside the method calling block is printed, and the block reads the name variable from the yield statements.
A method is defined, and yield statements are written within the method. These yield statements provide certain names as parameters, which will be printed when these methods are called.
def yieldExample
yield "ABC"
puts "Inside the method yieldExample"
yield "DEF"
end
yieldExample {|name| puts "Your name is #{name}"}
Your name is ABC
Inside the method yieldExample
Your name is DEF
Example #6
In the case of explicit blocks, the call is the equivalent of yield. By invoking a call on a block reference, you may immediately invoke it.
def code_block
puts 'Start of method'
# you can call the block using the yield keyword.
yield
puts 'End of method'
yield
end
code_block {puts 'Hit the block!'}
Start of method
Hit the block!
End of method
Hit the block!
Here, the term yield was used to specify where the provided code block would be executed. This is how blocks interact with methods; as we saw in the example above, yield may also accept arguments:
def code_block
yield 42
puts "You are in the method"
yield 84
end
code_block {|i| puts "You are in the block and have passed in this: #{i}"}
You are in the block and have passed in this: 42
You are in the method
You are in the block and have passed in this: 84
Conclusion
We discussed some simple examples of using Ruby’s “yield” keyword. Also, the foundations of the yield in Ruby, along with learning the use of yield to call a block from any function and that yield may be provided with numerous parameters to the block were discussed.