How to Use the Ruby add Method

09/26/2021

Contents

In this article, you will learn how to use the Ruby add method.

Using the add method

The Ruby add method is a built-in method that is used to add two or more numeric values together.

Syntax

The syntax for the add method is as follows:

add(number1, number2, ...)

Here, number1 and number2 are the values to be added together. You can add more than two numbers by separating each number with a comma.

Examples

To use the add method, you can simply call it and pass in the numbers you want to add as arguments. For example:

result = add(3, 4)
puts result # Output: 7

In this example, we pass in the values 3 and 4 to the add method, and the method returns the sum of the two numbers, which is 7. We then store the result in a variable called result and output it using the puts method.

You can also use the add method with variables. For example:

a = 5
b = 7
result = add(a, b)
puts result # Output: 12

Here, we define two variables a and b, each with a numeric value. We then pass these variables as arguments to the add method, which returns the sum of the two variables.

You can even add more than two numbers using the add method. For example:

result = add(2, 4, 6, 8)
puts result # Output: 20

In this example, we pass in four numbers to the add method, and the method returns the sum of all four numbers, which is 20.

The add method can also be used with floats or decimal values. For example:

result = add(1.5, 2.5)
puts result # Output: 4.0

In this example, we pass in two decimal values to the add method, and the method returns the sum of both values, which is 4.0.