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: yield allows us to inject blocks into a function at any point.

Let’s run a simple yield program without arguments:

def yield_func
puts "In the yield method"
yield
puts "Again back to yield method"
yield
end
yield_func{puts "This is a block"}

Explanation

  • Lines 2 to 5: We add two yield and puts statements.
  • Line 7: We pass a block to the yield_func function.

Yield with arguments

We can pass more than one parameter after yield. There are verticle lines (||) that accept such parameters:

def yield_func
yield 5*5
puts "In the method yield_func"
yield 100
end
yield_func{|i| puts "block #{i}"}

Explanation

  • Lines 2 to 4: We add two yield and puts statements.
  • Line 6: We passed a block with an argument i to the yield_func function. The number in the yield statement 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_return
value = yield
puts value
end
yield_func_return {"Yield return value"}

Explanation

  • 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

Copyright ©2025 Educative, Inc. All rights reserved