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

  • برمجة
  • برمجة روبي

 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.

الأجوبة

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]
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...