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?
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework