DEV Community

Cover image for Simple Explanation of Yield in Ruby
Shaher Shamroukh
Shaher Shamroukh

Posted on

5 2

Simple Explanation of Yield in Ruby

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
Enter fullscreen mode Exit fullscreen mode

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!" }
Enter fullscreen mode Exit fullscreen mode

Or we can do this

yield_example do
  puts "the method has yielded our block!"
end
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

To avoid that we can do this

def yield_example
  yield if block_given?
end
Enter fullscreen mode Exit fullscreen mode

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.

DEV Challenges are live now!

DEV Challenges Hub

Check out all the ways to participate, certify your skills, and win prizes.

Visit the Challenges Hub

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay