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:

Press + to interact
def add_two(number)
number + 2
end
puts 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.

  1. 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.
  2. To do so, it first needs to look at what’s inside the parentheses () so it can pass it on. It finds the 3. At this point, it creates a new local variable, number, and assigns the number 3 to it.
  3. Now, Ruby is ready to execute the method body by passing the number 3.
  4. 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:

Press + to interact
number = 3
return 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 assigned 3, the number+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:

Press + to interact
puts 5

That now prints the number 5 to the screen.