Y U No Return My Ruby

One thing that is obvious when I switch from JavaScript exercises to Ruby ones (despite the curly brackets of course) is the prolific use of “return” in JavaScript.

For example if I wanted to create an addition function in JS, this is how the code would look:


function additionFunction(a, b) {
  return a + b;
}

Without the “return” inside the function block the additionFunction would not work.

On the other hand, “return” in Ruby in this case is optional. Both examples below would work fine.


def addition_method(a, b) 
  a + b
end


def addition_method(a, b) 
 return a + b
end

This is when ones asks: “Soooo What do is the reason of “return” then in Ruby? Why have it in the language?” One answer is that specifying “return” in Ruby is syntactic sugar– just a way to be more descriptive with your code.

Well, at least this is what I thought until recently. Yesterday I paired with my good friend and great developer Francis Gulotta and, as usually happens when I pair program, I learned something.

I learned that “return” in Ruby also allows you to break out of a method early.

Consider the if/else statement below:


1 def return_absolute_number(number)
2   if number > 0
3     number 
4   else
5    - (number)
6   end
7 end

As the name suggests, the return_absolute_number method returns the absolute value of an integer. It will run line 7 if the number is positive or the else block if we are dealing with a negative number.

But this method could also be written like this:


1 def return_absolute_number(number)
2   if number > 0
3    return number 
4   end
5   - (number)
6 end

“Return” here prevents the program from running past line 3 if the condition on line 2 is met. Line 5 only gets returned if the condition isn’t met on line 2. Pretty interesting, huh?

I could even write this method in this manner:

 
1 def return_absolute_number(number)
2  return number if number > 0
3  - (number)
4 end

This method would break out early and would stop running on line 2 if number is greater than zero. Otherwise, line 3 would be returned.

Moral of the story: there is always a reason to return.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s