Ruby Array Exercises: Compute the sum of the first 2 elements of a given array of integers
Ruby Array: Exercise-14 with Solution
Write a Ruby program to compute the sum of the first 2 elements of a given array of integers. If the array length is less than 2, just sum up the elements that exist, returning 0 if the length of the array is 0.
Ruby Code:
def check_array(nums)
if(nums.length >= 2)
return (nums[0] + nums[1])
end
if(nums.length == 1)
return nums[0];
end
return 0;
end
print check_array([1, 2, 5]),"\n"
print check_array([4, 2, 3]),"\n"
print check_array([1])
Output:
3 6 1
Flowchart:
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Ruby program to find the larger between the first and last elements of a given array of integers and length 3. Replace all the other values to be that value. Return the changed array.
Next: Write a Ruby program to create an array of length 2 containing their middle elements from two given arrays of integers and length 3.
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