Combining Methods

Learn how to use methods within methods.

We'll cover the following

We’ve discussed how to define a method and how to call it. What if one method isn’t enough? What if methods need to do more complicated things?

Callings methods from another method

For example, we could rewrite our add_two method using another add_one method and simply call it twice:

Press + to interact
def add_one(number)
number + 1
end
def add_two(number)
number = add_one(number)
add_one(number)
end
puts add_two(3)

This outputs 5 just like our previous examples.

We could also solve this whole problem by simply using the + operator.

However, for the sake of the example, let’s have a look at how we could add a method that does the exact same thing as the + operator:

Press + to interact
def sum(number, other)
number + other
end
Press + to interact
puts sum(3, 2)

Which, again, outputs 5.

Note that in this example, our sum method now takes two arguments. When we call it, we also need to pass two numbers.

With this method in place, we can change (refactor) our previous methods to use it:

Press + to interact
def sum(number, other)
number + other
end
def add_one(number)
sum(number, 1)
end
def add_two(number)
sum(number, 2)
end
puts add_one(3)
puts add_two(3)

Again, these examples aren’t very realistic because we’d probably just use the + operator in practice.

However, this nicely demonstrates how we can call one method from another and how different methods require different numbers of arguments.