Simple Explanation of Yield in Ruby
Shaher Shamroukh
Posted on April 4, 2021
Yield meaning in ruby
the yield keyword is used inside methods for calling a block which is a bit of code enclosed in do/end keywords or curly brackets {}.
we have to understand blocks well in order to understand the yield keyword and what does it do.
this article assumes the reader has a good understanding of ruby blocks.
so the yield keyword is basically telling the method to stop executing the code in this method, and instead execute the code in this block. then, return to the code in the method.
here is an example:
def yield_example
puts "the program is now executing the code inside this method"
yield
puts "now we are back in the method after executing the block"
end
Now to call this method with a block, we use the name of the method and append the block:
yield_example { puts "the method has yielded our block!" }
Or we can do this
yield_example do
puts "the method has yielded our block!"
end
Now When we call the #yield_example method with the above block, the output will be:
the program is now executing the code inside this method
the method has yielded our block!
now we are back in the method after executing the block
Note that If we call yield without having a block, then we will get an error.
Here is an example:
def yield_example
yield
end
yield_example
# LocalJumpError: no block given (yield)
To avoid that we can do this
def yield_example
yield if block_given?
end
The block_given? method checks if a block is available and this will allow us to only yield if the block is given.
Conclusion
This was a simple explanation of yield in ruby and there is more to it than that so check out this on stackoverflow
and Ruby-doc for more information.
Posted on April 4, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.