Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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

Ruby Array: Exercise-20 with Solution

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

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: 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.

What is the difficulty level of this exercise?