# How to Use the Ruby sum Method

09/24/2021

Contents

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

## Using the sum method

The sum method in Ruby is a built-in method that allows you to find the sum of an array of numbers or elements. The sum method can be used with an array of integers, floats, and strings that can be converted to numbers.

Here is how you can use the sum method in Ruby:

### Using an array of integers

``````array = [1, 2, 3, 4, 5]
sum = array.sum
puts sum # Output: 15
``````

In this example, we have an array of integers and we call the sum method on it. The sum method calculates the sum of all the elements in the array and returns it. The output will be 15.

### Using an array of floats

``````array = [1.0, 2.5, 3.2, 4.7, 5.9]
sum = array.sum
puts sum # Output: 17.3
``````

In this example, we have an array of floats and we call the sum method on it. The sum method calculates the sum of all the elements in the array and returns it. The output will be 17.3.

### Using an array of strings that can be converted to numbers

``````array = ["1", "2", "3", "4", "5"]
sum = array.sum(&:to_i)
puts sum # Output: 15
``````

In this example, we have an array of strings that can be converted to numbers and we call the sum method on it. We pass &:to_i as an argument to the sum method. This converts each string element to an integer before calculating the sum. The output will be 15.

### Using a block

``````array = [1, 2, 3, 4, 5]
sum = array.sum { |n| n * 2 }
puts sum # Output: 30
``````

In this example, we have an array of integers and we call the sum method on it with a block. The block takes each element in the array and multiplies it by 2. The sum method then calculates the sum of all the modified elements and returns it. The output will be 30.

### Using an optional argument

``````array = [1, 2, 3, 4, 5]
sum = array.sum(10)
puts sum # Output: 25
``````

In this example, we have an array of integers and we call the sum method on it with an optional argument of 10. This means that the sum of all the elements in the array will be calculated and added to the value of 10. The output will be 25.