Yield keyword in Ruby Programming

RubyServer Side ProgrammingProgramming

There are often cases where we would want to execute a normal expression multiple times inside a method but without having to repeat the same expression again and again. With the yield keyword, we can do the same.

We can also pass arguments to the yield keyword and get values in return as well. Now let's explore some examples to see how the yield keyword works in Ruby.

Example 1

Consider the code shown below where we are declaring a normal yield keyword twice inside a method and then calling 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!"}

Output

It will generate the following output −

In the tuts method
Yield executed!
Again back to the tuts method
Yield executed!

Example 2

Now let's try to add arguments to the yield keyword as well. Consider the code shown below.

def tuts
   yield 2*5
   puts "In the method tuts"
   yield 150
end
tuts {|i| puts "yield #{i}"}

Output

If we write the following code on any Ruby IDE, then we will get the following output in the terminal.

yield 10
In the method tuts
yield 150

Example 3

Now finally, let's see an example where we would return value from a yield in Ruby. Consider the code shown below.

def return_value_yield
   tutorials_point = yield
   puts tutorials_point
end
return_value_yield { "Welcome to TutorialsPoint" }

Output

If we write the following code on any Ruby IDE, then we will get the following output in the terminal.

Welcome to TutorialsPoint
raja
Updated on 25-Jan-2022 10:33:05

Advertisements