Yield Keyword In Ruby

Yahya Gok
2 min readApr 25, 2021

Yield is a keyword. It’s used inside methods for calling a block.

Let’s explain this with an example. We have a method name write_letter and we want to see how this yield work here. As you can see we have three yield keyword here with yield. if we call that method with brackets

like this;

write_letter { |starting_letter| puts “ “#starting_letter”} I hope you are well” . Here, the code between the curly brackets is the code block.

def write_letter
yield "Hi, Mr. Adam"
yield "Hi, Miss.Lisa"
yield "Hi, Miss Carolina"
end

write_letter { |starting_letter| puts "#{starting_letter} I hope you are well" }

So, output will be like this with three string. Because we declare three times yield keyword.

Let’s do a little example here to get the concept well.

Here in this example with some_string method. We executed the method with this some_string and the with brackets { } we typed "yield is here". Ruby replace this yield keyword with the puts.

def some_strings
puts "We have yield keyword in down"
yield
puts "look at the output you will the yield "
end
some_strings { puts "yield is here" }

Resources

--

--