find the sum of a list of numbers in ruby

In Ruby, we can find the sum of a list of numbers using the reduce method or its alias inject.

main.rb
# using reduce
list = [1, 2, 3, 4, 5]
sum = list.reduce(0) {|acc, num| acc + num}
puts sum #=> 15

# or using inject
list = [1, 2, 3, 4, 5]
sum = list.inject(0) {|acc, num| acc + num}
puts sum #=> 15
200 chars
10 lines

In the above code, we first define a list of numbers. We then use either reduce or inject method to iterate over the list and calculate the sum. Both methods take an initial value for the accumulator variable (0 in this case) and a block that specifies how to accumulate the sum. The block receives two parameters, acc which is the initial value (or the value returned by the last iteration) and num which is the current number in the list. The block then returns the updated value of the accumulator. Finally, we print the sum to the console.

related categories

gistlibby LogSnag