Return - Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Return

The return statement will be our escape pod. We'll be using it to exit when or if a condition is met. Here's an example:

def lazy_calculator(x,y)

return "That's too much. I'm out." if x + y > 20

puts x * y

end

lazy_calculator(17,5)

That's too much. I'm out.

Our method didn't puts x*y. How lazy. It's because we used return. Change return to puts.

def lazy_calculator(x,y)

puts "That's too much. I'm out." if x + y > 20

puts x * y

end

lazy_calculator(17,5)

That's too much. I'm out.

85

By using puts we didn't have an escape pod to leave our method with. I use the term "lazy" here because it befits the example. Methods that use return aren't actually lazy. They act as gatekeepers. "Game of Thrones" fans can think of them as, The Night's Watch. Even still, that's just one more way of thinking about return.

Replace puts with return in our block.

def trees

leaf = Proc.new {return "I'm blowing in the wind."}

leaf.call

print "I'm standing still."

end

trees

I'm blowing in the wind.

Our proc returns immediately and does not go back to the calling method.

Replace the proc with a lambda.

def trees

leaf = lambda {return "I'm blowing in the wind."}

leaf.call

print "I'm standing still."

end

trees

I'm standing still.

Because there was something to return within the method our lambda ceded to it. If we removed the print "I'm standing still.", our string in the block would be returned.

def trees

leaf = lambda {return "I'm blowing in the wind."}

leaf.call

end

trees

I'm blowing in the wind.

Because there was nothing to return to in the method, what was in our block was returned.