w3resource

Ruby Array Exercises: Iterate over the first n elements of a given array

Ruby Array: Exercise-47 with Solution

Write a Ruby program to iterate over the first n elements of a given array.

Ruby Array Exercises: Iterate over the first n elements of a given array

Ruby Code:

arra1 = ['abcde', 'abdf', 'adeab', 'abdgse', 'bdefa', 'bacdef']
print "Original array:\n"
print arra1
arra2 = arra1.first(3)
print "\nFirst 3 elements:\n"
print arra2

Output:

Original array:
["abcde", "abdf", "adeab", "abdgse", "bdefa", "bacdef"]
First 3 elements:
["abcde", "abdf", "adeab"]

Flowchart:

Flowchart: Iterate over the first n elements of a given array

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to iterate an array starting from the last element.
Next: Write a Ruby program to iterate over the first n elements of a 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://www.w3resource.com/ruby-exercises/array/ruby-array-exercise-47.php