In Ruby, we can find the sum of a list of numbers using the reduce method or its alias inject.
main.rb200 chars10 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.
gistlibby LogSnag