-
Book Overview & Buying
-
Table Of Contents
The Ruby Workshop
By :
Methods are great for wrapping up blocks of code that accomplish some purpose. In many cases, we want to capture the results of that code execution in one or more variables. As such, the method can return these variables to the caller of the method. Conveniently enough, the keyword for returning variables is return.
Here is a basic case of adding two numbers:
def sum(var1, var2) return var1 + var2 end
In Ruby, the value of the last line of code in a method is implicitly returned, so we also write this as follows:
def sum(var1, var2) var1 + var2 end total = sum(1, 3)
The choice to do one or the other depends on the developer's style and the requirements of the program.
The Ruby style guide says to avoid the use of the return keyword when not required for flow control.
Ruby methods can also return multiple values. Let's take a look at some simple examples.
The following method returns...
Change the font size
Change margin width
Change background colour