Usage
Learn how to use methods in Ruby after defining them.
We'll cover the following
Calling a method
We can only use a method after we’ve defined it. As programmers, we usually say that we call a method. This means we ask Ruby to execute the code that the method body has, with some given arguments (if any).
Here’s how that looks:
def add_two(number)number + 2endputs add_two(3)
Explanation
Let’s inspect what’s happening here in more detail, though it might seem confusing at first
In the first three lines, Ruby defines the add_two
method as discussed before. Line 4 contains no code, so Ruby ignores it.
- In line 5, Ruby looks at the
add_two(3)
first. It recognizes that we’re referring to a method defined earlier, and this tells it that we want to call (execute) this method. - To do so, it first needs to look at what’s inside the parentheses
()
so it can pass it on. It finds the3
. At this point, it creates a new local variable,number
, and assigns the number3
to it. - Now, Ruby is ready to execute the method body by passing the number
3
. - So, Ruby now deviates from the normal flow, which just goes from top to bottom in our file. Instead, it now jumps into the method body.
This is how method arguments work:
When a method is called and objects are passed as arguments, then Ruby implicitly defines local variables with the argument names. It assigns the passed objects to the variable names in the argument list. These local variables are then available in the method body.
In our case, we have just one argument, number
. So, we get one local number
variable with the object, 3
, assigned because that’s the object passed when we called the method.
We can imagine that the method body now reads like this:
number = 3return number + 2
Inside the method body:
- Ruby executes (evaluates, runs) the method body (again, going from top to bottom), which in our case is just a single line with the expression
return number + 2
. - Because
number
is assigned3
, thenumber+2
expression evaluates to 5, and this is the value that is returned from the method call.
Ruby now jumps back out of the method. The add_two(3)
expression returns the object 5
. Imagine the last line now reads like this instead:
puts 5
That now prints the number 5
to the screen.