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.rb52 chars4 lines
Output:
main.rb3 chars2 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.rb52 chars4 lines
Output:
main.rb3 chars2 lines
The inject method works in the same way as the reduce method, and you can use either one depending on your preference.
gistlibby LogSnag