Method Definition

Define our method in Ruby.

We'll cover the following

Stand-alone methods

So far, we’ve seen methods that are defined on objects and can be called on objects. That is, we’ve seen the downcase method that’s defined on every string.

However, Ruby also allows for methods that aren’t defined on any of these objects. They’re sort of stand-alone methods.

For example, we can try this out:

Press + to interact
puts is_a?(Object)

We’ll focus on this type of method in this chapter because we want to focus on the characteristics of methods. Take a look at the bonus chapter about the top-level object.to learn more about them. We’ll also learn how to define the methods for our own classes later.

Ok, let’s get started.

Defining a method

Suppose we need to define a simple method that takes a number, adds the number 2 to it, and returns the result. Here’s how we can do that:

Press + to interact
def add_two(number)
number + 2
end

This defines a method, but it doesn’t use it yet. We only build and place that vending machine so it can be used later.

Let’s walk through this method definition step by step:

  1. Ruby reads the code at the top and finds the def keyword. This tells Ruby that we’re about to define a new method.
  2. Methods need a name, so Ruby looks for it and finds the word add_two.
  3. Ruby then checks if we define anything to serve as input to the method (remember, this is optional). It finds the parentheses and determines that we’re about to define a list of things that can be given to the method. This list is called an argument list.

Remember: An argument list defines names for objects passed to the method, enclosed by parentheses after the method name.

  1. In our case, the argument list has one single argument, number, which means our method can accept one thing (object).
  2. The next line is the block of code that our method has (the code it encapsulates). This is also referred to as the method body. In our case, that’s just a single line because the operation our method encapsulates is very simple. Other methods (sort, defined on arrays, for example) require more code and are longer.
  3. Inside the method body, the arguments are known as local variables. Notice how the code in our method body uses the variable name number.
  4. Finally, the end keyword tells Ruby that we’re done with the method body and the method definition.

All we’ve done so far is define the method. We haven’t used it for anything, yet. We’ll do that in the next chapter.

Note: The keywords def and end sit on the same level, while the method body is indented by two spaces. Also note how there is no space before or inside the argument list, or the () parentheses.