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 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:
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?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/ruby-exercises/array/ruby-array-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics