Q:

Write a Ruby program to create a new array using first three elements of a given array of integers

0

 Write a Ruby program to create a new array using first three elements of a given array of integers. If the length of the given array is less than three return the original array.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

def check_array(nums)
    front = []
	if nums.length >= 3
		front[0] = nums[0]
		front[1] = nums[1]
		front[2] = nums[2]
	elsif nums.length == 2
		front[0] = nums[0]
		front[1] = nums[1]
	else nums.length == 1
	    front[0] = nums[0]
	end
	return front
end

print check_array([1, 3, 4, 5]),"\n"
print check_array([1, 2, 3]),"\n"
print check_array([1,2]),"\n"
print check_array([1]),"\n" 
 Output:
[1, 3, 4]
[1, 2, 3]
[1, 2]
[1]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now