w3resource

Ruby Array Exercises: Compute the sum of elements in a given array

Ruby Array: Exercise-5 with Solution

Write a Ruby program to compute the sum of elements in a given array.

Ruby Array Exercises: Compute the sum of elements in a given array

Ruby Code:

nums = [12, 34, 23, 56]
print "Original array:\n"
print nums
print "\nSum of the values of the above array:\n"
print nums.inject(0){|sum,x| sum + x }

Output:

Original array:
[12, 34, 23, 56]
Sum of the values of the above array:
125

Flowchart:

Flowchart: Compute the sum of elements in a given array

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check whether first and the last element are the same of an given array of integers. The array length must be 1 or more.
Next: Write a Ruby program to remove duplicate elements from an given array.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.