w3resource

Ruby Basic Exercises: Check whether the sequence of numbers 10, 20, 30 appears anywhere in a given array of integers

Ruby Basic: Exercise-43 with Solution

Write a Ruby program to check whether the sequence of numbers 10, 20, 30 appears anywhere in a given array of integers.

Ruby Code:

def array102030(nums)
    idx = 0
    while idx < nums.length-2
        if nums[idx..idx+2] == [10,20,30]
            return true
        end
        idx += 1
    end
    return false
end
print array102030([10, 20, 30, 40, 50]),"\n"
print array102030([0, 10, 20, 30, 90]),"\n"
print array102030([10, 20, 50, 30, 70])

Output:

true
true
false

Flowchart:

Flowchart: Check whether the sequence of numbers 10, 20, 30 appears anywhere in a given array of integers

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check whether one of the first 5 elements in a given array of integers is a 7. The array length may be less than 5.
Next: Write a Ruby program to compute and print the sum of two given integers, print 30 if the sum is in the range 20..30 (inclusive).

What is the difficulty level of this exercise?