Ruby Array Exercises: Create a new array from the middle of a given array of integers of odd length
Ruby Array: Exercise-25 with Solution
Write a Ruby program to create a new array of length 3 containing the elements from the middle of a given array of integers of odd length (at least 3).
Ruby Code:
def check_array(nums)
halfArr = [];
half = nums.length/2;
halfArr[0] = nums[half-1];
halfArr[1] = nums[half];
halfArr[2] = nums[half+1];
return halfArr;
end
print check_array([1, 3, 4]),"\n"
print check_array([1, 2, 3, 7, 9])
Output:
[1, 3, 4] [2, 3, 7]
Flowchart:
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Ruby program to swap the first and last elements of a given array of integers, length will be at least 1. Return the modified array.
Next: Write a Ruby program to find the largest value from a given array of integers of odd length. The array length will be a least 1.
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-25.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics