Forwarding
Forwarding

Reputation: 245

How to loop through an array using .each starting at an index in Ruby

Ok, so we all know that you can do the following:

array.each{ |value|
    puts value
}

What if, however, I want to start at element n instead of starting at the beginning; i.e. n=0.

Upvotes: 1

Views: 725

Answers (2)

user3723506
user3723506

Reputation:

You can also do

array.drop(n).each { |v| puts v }

Upvotes: 2

Matthew Galloway
Matthew Galloway

Reputation: 157

You can call a subarray with a range like this:

array[n..-1].each { |value| puts value }

Where n is the index you'd like to start at, and -1 will always point to the last index of an array.

Upvotes: 1

Related Questions