In many programming languages, a distinction is made between functions or methods that return a value to the calling code and those that do not. In Pascal, for example, a function returns a value, but a procedure does not. No such distinction is made in Ruby. All methods always return a value, though of course you are not obliged to use it.
When no return value is specified, Ruby methods return the result of the last expression evaluated. Consider this method:
return_vals.rb
def method1 a = 1 b = 2 c = a + b # returns 3 end
The last expression evaluated is a + b
, which happens to return 3, so that is the value returned by this method. There may often be times when you don’t want to return the last expression evaluated. In such cases, you can specify the return value using the return
keyword:
def method2 a = 1 b = 2 c = a + b return b # returns 2 end
A method is not obliged to make any assignments in order to return a value. If a simple piece of data happens to be the last thing evaluated in a method, that will be the value the method returns. When nothing is evaluated, nil
is returned:
def method3 "hello" # returns "hello" end def method4 a = 1 + 2 "goodbye" # returns "goodbye" end def method5 end # returns nil
My own programming prejudice is to write code that is clear and unambiguous whenever possible. For that reason, whenever I plan to use the value returned by a method, I prefer to specify it using the return
keyword; only when I do not plan to use the returned value do I omit this. However, this is not obligatory—Ruby leaves the choice to you.