Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the point of return in Ruby?

Tags:

return

ruby

What is the difference between return and just putting a variable such as the following:

no return

def write_code(number_of_errors)   if number_of_errors > 1      mood = "Ask me later"   else      mood = "No Problem"   end     mood end 

return

def write_code(number_of_errors)   if number_of_errors > 1     mood =  "Ask me later"   else     mood = puts "No Problem"   end     return mood end 
like image 797
thenengah Avatar asked Jan 05 '11 06:01

thenengah


People also ask

What does return in Ruby do?

In Ruby, a method always return exactly one single thing (an object). The returned object can be anything, but a method can only return one thing, and it also always returns something. Every method always returns exactly one object.

Is return necessary in Ruby?

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.

What is the purpose of return?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function. For more information, see Return type.

Why do we use return keyword?

The return keyword finished the execution of a method, and can be used to return a value from a method.


1 Answers

return allows you to break out early:

def write_code(number_of_errors)   return "No problem" if number_of_errors == 0   badness = compute_badness(number_of_errors)   "WHAT?!  Badness = #{badness}." end 

If number_of_errors == 0, then "No problem" will be returned immediately. At the end of a method, though, it's unnecessary, as you observed.


Edit: To demonstrate that return exits immediately, consider this function:

def last_name(name)   return nil unless name   name.split(/\s+/)[-1] end 

If you call this function as last_name("Antal S-Z"), it will return "S-Z". If you call it as last_name(nil), it returns nil. If return didn't abort immediately, it would try to execute nil.split(/\s+/)[-1], which would throw an error.

like image 137
Antal Spector-Zabusky Avatar answered Oct 19 '22 20:10

Antal Spector-Zabusky