How to use yield in Rails 6
Overview
Block is an anonymous function that can be passed to the methods. It can either be enclosed between brackets {} or in a do/end. We can also pass multiple arguments in a block.
If we want to call a block multiple times, we can pass it to our method by sending a proc or lamda. But yield is more convenient and quicker in Rails 6 for the same task.
Note:
yieldallows us to inject blocks into a function at any point.
Let’s run a simple yield program without arguments:
def yield_funcputs "In the yield method"yieldputs "Again back to yield method"yieldendyield_func{puts "This is a block"}
Explanation
- Lines 2 to 5: We add two
yieldandputsstatements. - Line 7: We pass a block to the
yield_funcfunction.
Yield with arguments
We can pass more than one parameter after yield. There are verticle lines (||) that accept such parameters:
def yield_funcyield 5*5puts "In the method yield_func"yield 100endyield_func{|i| puts "block #{i}"}
Explanation
- Lines 2 to 4: We add two
yieldandputsstatements. - Line 6: We passed a block with an argument
ito theyield_funcfunction. The number in theyieldstatement is printed along with the block.
Yield with return value
We can also return a value from a function using the yield statement.
def yield_func_returnvalue = yieldputs valueendyield_func_return {"Yield return value"}
Explanation
-
Lines 2 and 3: We assign
yieldto a variablevalue. Then we print it using theputsstatement. -
Line 5: We pass a block to the
yield_func_returnfunction.
Free Resources