The yield Keyword in Ruby

We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with in it. A block is simply a chunk of code, and yield allows us to inject that code at some place into a method.

Simple Yield: When the yield keyword used inside the body of a method, will allow us to call that method with a block of code. Below is simple yield program to understand.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of using yield keyword
def geeks
   puts "In the geeks method"
  
   # using yield keyword
   yield
   puts "Again back to the geeks method"
   yield
end
geeks {puts "This is block"}

chevron_right


Output:

In the geeks method
This is block
Again back to the geeks method
This is block

 
Yield with argument: Below is the program of yield with argument.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of using yield keyword 
# with argument
def gfg
   yield 2*3
   puts "In the method gfg"
   yield 100
end
gfg {|i| puts "block #{i}"}

chevron_right


Output :



block 6
In the method gfg
block 100

In above example, the yield statement is written followed by parameters. we can even pass more than one parameter after yield. To accept the parameters we placed a variable(i) between two vertical lines (||).

Yield with Return value: It is possible to get the return value of a block by simply assigning the return value of a yield to a variable. if we use yield with an argument, it will pass that argument to the block.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of using yield keyword
# with return value
def yield_with_return_value
  geeks_for_geeks = yield
  
  puts geeks_for_geeks
end
  
yield_with_return_value { "Welcome to geeksforgeeks"

chevron_right


Output:

Welcome to geeksforgeeks

The geeks_for_geeks variable get the “Welcome to geeksforgeeks” returned by the block and display it by using puts.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.