w3resource

Ruby Array Exercises: Find the larger between the first and last elements of a given array of integers

Ruby Array: Exercise-13 with Solution

Write a Ruby program to find the larger between the first and last elements of a given array of integers of length 3. Replace all the other values to be that value. Return the changed array.

Ruby Array Exercises: Find the larger between the first and last elements of a given array of integers

Ruby Code:

def check_array(nums)
    maxVal = []
   	maxVal[0] = nums[0]
	if(nums[2] >= maxVal[0])
		maxVal[0] = nums[2]
	maxVal[1] = maxVal[0]
	maxVal[2] = maxVal[0]
	end
	return maxVal
end
print check_array([1, 2, 5]),"\n" 
print check_array([1, 2, 3]),"\n" 
print check_array([1, 2, 4])  

Output:

[5, 5, 5]
[3, 3, 3]
[4, 4, 4]

Flowchart:

Flowchart: Find the larger between the first and last elements of a given array of integers

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to create a new array with the elements in reverse order from a given an array of integers of length 3.
Next: Write a Ruby program to compute the sum of the first 2 elements of a given a 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.

What is the difficulty level of this exercise?