w3resource

Ruby Array Exercises: Check whether 7 appears as either the first or last element in a given array

Ruby Array: Exercise-2 with Solution

Write a Ruby program to check whether 7 appears as either the first or last element in a given array. The array length must be 1 or more.

Ruby Array Exercises: Check whether 7 appears as either the first or last element in an given array

Ruby Code:

def check_array(nums)
   return (nums[0] == 7 || nums[nums.length-1] == 7)
end
print check_array([1, 2, 7]),"\n"
print check_array([7, 1, 2, 3]),"\n"
print check_array([14, 7, 1, 2, 3])

Output:

true
true
false

Flowchart:

Flowchart: Check whether 7 appears as either the first or last element in a given array

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check if a value exists in an array.
Next: Write a Ruby program to pick number of random elements from an given array.

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://w3resource.com/ruby-exercises/array/ruby-array-exercise-2.php