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:
def add_one(number)number + 1enddef add_two(number)number = add_one(number)add_one(number)endputs 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:
def sum(number, other)number + otherend
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:
def sum(number, other)number + otherenddef add_one(number)sum(number, 1)enddef add_two(number)sum(number, 2)endputs 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.