find the sum of all elements in an array in ruby

To find the sum of all elements in an array in Ruby, you can use the reduce (also known as inject) method. The reduce method combines all elements of the array by applying a binary operation.

Here's an example:

main.rb
arr = [1, 2, 3, 4, 5]
sum = arr.reduce(:+)
puts sum
52 chars
4 lines

Output:

main.rb
15
3 chars
2 lines

In this example, we define an array arr with values [1, 2, 3, 4, 5]. We then use the reduce method to add all elements of the array using the binary operator :+. The result is assigned to the variable sum, which is then printed to the console. The output is the sum of all the elements in the array, which is 15.

Alternatively, you can also use the inject method in a similar way:

main.rb
arr = [1, 2, 3, 4, 5]
sum = arr.inject(:+)
puts sum
52 chars
4 lines

Output:

main.rb
15
3 chars
2 lines

The inject method works in the same way as the reduce method, and you can use either one depending on your preference.

related categories

gistlibby LogSnag