What does the word “yield” mean in Ruby? And what does it do exactly?
Well…
Yield is a keyword (meaning it’s a core part of the language) & it’s used inside methods for calling a block.
Here’s what you need to know:
yield
You have to understand blocks for this to make sense.
You can think of blocks as methods without names that can be passed as extra arguments to other methods.
Here’s an example:
def make_salad yield "lettuce" yield "carrots" yield "olive oil" end make_salad { |ingredient| puts "Adding #{ingredient} to salad!" }
This calls the block 3 times, producing this output:
Adding lettuce to salad! Adding carrots to salad! Adding olive oil to salad!
That’s in essence what yield
does, is like calling a method, but instead you’re calling the block.
We don’t have a name for the block, so this keyword takes care of that.
Now:
Let’s explore what happens if you don’t have a block to call.
If you call yield
without having a block, then you get an error.
Example:
def write_code yield end write_code # LocalJumpError: no block given (yield)
This error is crystal-clear, “no block given” means that the method call write_code
is not providing a block.
How can you prevent this error?
Like this:
def write_code yield if block_given? end
The block_given?
method checks if a block is available & this allows you to only yield
if that’s true.
Using yield
enables blocks.
We use blocks to pass in bits of code as part of a method call.
That’s helpful when:
Hash#fetch
method)Nice!
You may find this new yield_self
method & think it’s related to yield
.
Well, it isn’t.
Even yield(self)
is different, because self refers to the current object.
Where yield_self
, which was was added in Ruby 2.5, refers to the object we’re calling the method on.
A good use for this method?
Use it whenever you want to chain methods & do something with the object you’re calling yield_self
on.
While returning the results, instead of the original object.
Example:
n_squared = ->(n) { n ** 2 } 2 .yield_self(&n_squared) .yield_self(&n_squared) # 16
In Ruby 2.6, there is an alias for yield_self
, the then
method.
But don’t confuse it with your regular yield
.
Ok?
I should also give a quick mention to the use of yield
in Rails & templating engines.
You’ll find yield
inside layouts.
Rails replaces it with the contents of the view you’re rendering.
No yield
equals empty layout!
That’s how the layout & your views are combined together.
You have learned about the yield keyword in Ruby! Exactly what it is, how it works & why it matters.
Now give it a try in your Ruby code.
Thanks for reading! 🙂