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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/ruby-exercises/array/ruby-array-exercise-20.php