Ruby Array Exercises: Swap the first and last elements of a given array of integers
Ruby Array: Exercise-24 with Solution
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.
Ruby Code:
def check_array(nums)
temp = nums[0];
nums[0] = nums[nums.length-1];
nums[nums.length-1] = temp;
return nums;
end
print check_array([1]),"\n"
print check_array([1, 3]),"\n"
print check_array([1, 3, 5]),"\n"
print check_array([11, 3, 5, 21])
Output:
[1] [3, 1] [5, 3, 1] [21, 3, 5, 11]
Flowchart:
-->
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Ruby program to create a new array of length 4 containing all their elements from two array of integers, length 2.
Next: Write a Ruby program to create a new array length 3 containing the elements from the middle of a given array of integers of odd length (at least 3).
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-24.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics