w3resource

Ruby Array Exercises: Set 5 to 1 if there is a 3 immediately followed by a 5 in a given array of integers


Write a Ruby program to set 5 to 1 if there is a 3 immediately followed by a 5 in a given array of integers (length 3).

Ruby Code:

def check_array(nums)
     num1 = nums[0], nums[1], nums[2]
	if(nums[0] == 3 && nums[1] == 5)
			num1[1] = 1;
	end		
	if(nums[1] == 3 && nums[2] == 5)
			num1[2] = 1;
	end		
	return num1;
end
print check_array([1, 3, 5]),"\n" 
print check_array([3, 5, 6]),"\n" 
print check_array([3, 9, 5])  

Output:

[1, 3, 1]
[3, 1, 6]
[3, 9, 5]

Flowchart:

Flowchart: Set 5 to 1 if there is a 3 immediately followed by a 5 in a given array of integers

Go to:


PREV : Write a Ruby program to check whether a given array of integers contains 3 twice, or 5 twice. The array will be length 0, 1, or 2.
NEXT : Write a Ruby program to compute the sum of two arrays (length 3) and return the array which has the largest sum.

Ruby Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.