Ruby Blocks Return Values Tutorial

In this section, we will learn how to return a value from blocks in Ruby.

Note: we’re assuming you’re already familiar with Ruby blocks.

What is a block with return value in Ruby?

Block can return values as well!

Basically, the last expression that appears in the body of a block is its return value!

Note that we don’t use the return keyword when want to return a value to the caller of the method!

This is because the return keyword will be returned literally as a result (the return statement itself won’t run!) and so when this value is returned to the caller method of the block, it will cause the method to end its work. (The return statement runs when it appears in the method then!)

Example: returning a value from a block in Ruby

def block_function 
    result = yield "John","Doe"
    puts result
end 

block_function do |first_name, last_name|
    "Hello and welcome #{first_name} #{last_name}"
end

Output:

Hello and welcome John Doe

How does returning a value from a block work in Ruby?

In the example above, within the body of the block_function there’s a call to the yield keyword on the right side of the `result` variable.

This means after running the instructions within the body of the target block, the result will be passed to this variable then.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies