Let's write a method called reverse_sign
that takes one object - an Integer
- and changes a positive value to negative one, and vice-versa. We'll then dissect it, then move on to you practicing writing your own method.
There, that works perfectly, converting 100 to -100 and -5 to 5 by simply subtracting the number given from 0.
Let's dissect this example a little, and you can then practice by writing your own.
First, note that we use the def
keyword to create a method called reverse_sign
on the current object. Since Ruby doesn't allow us to use spaces in method names, we replace them with underscores instead. It's also recommended that, as a convention, method names be in lower case.
The reverse_sign
method accepts one parameter or argument. This is simply jargon for the objects a method needs from the caller in order for it to do its job. In this case, it's an integer. A method can accept any number of parameters (or none).
The return
keyword specifies the object to be returned to the caller when the method has done its work. If no return keyword is specified, the object created by the last line in the method is automatically treated as the return value. A method must always return exactly one object.
Finally, the method is closed using the end
keyword. There - simple, right?
As you can see, even a method that does nothing at all and has no return
produces an object - the nil
. I'm printing out the class name because printing a nil
returns an empty string, so you wouldn't see anything.
Be cautious when using return
- calling return
also exits the method at that point. No code in the method after the return
statement is executed.
This last example demonstrates two things:
-
The
return
exits the method; the puts
statement that comes right after is never run.
-
Calling
return
without specifying an object to return results in a nil
, which is returned by default.
An excellent practice is to either avoid using return
entirely or always use return in the last line of the method (which is effectively the same thing). Having a method exit in the middle is always surprising, so being consistent in this manner makes for code that's easier to understand.