Ruby Array Exercises: Create a new array of length 2 containing the middle two elements from a given array of integers of even length 2 or more
Ruby Array: Exercise-22 with Solution
Write a Ruby program to create a new array of length 2 containing the middle two elements from a given array of integers of even length 2 or more.
Ruby Code:
def check_array(nums)
midArr = []
half = nums.length/2;
midArr[0] = nums[half-1];
midArr[1] = nums[half];
return midArr;
end
print check_array([1, 3, 5, 4]),"\n"
print check_array([11, 3, 5, 21, 0, -4])
Output:
[3, 5] [5, 21]
Flowchart:
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Ruby program to compute the sum of two arrays (length 3) and return the array which has the largest sum.
Next: Write a Ruby program to create a new array of length 4 containing all their elements from two array of integers, length 2.
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