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:
yield
allows 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"}
yield
and puts
statements.yield_func
function.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}"}
yield
and puts
statements.i
to the yield_func
function. The number in the yield
statement is printed along with the block.We can also return a value from a function using the yield
statement.
def yield_func_returnvalue = yieldputs valueendyield_func_return {"Yield return value"}
Lines 2 and 3: We assign yield
to a variable value
. Then we print it using the puts
statement.
Line 5: We pass a block to the yield_func_return
function.
Free Resources