How do I set a starting offset for each
loop in ruby? I want the loop to begin from a[3]
instead of a[0]
. How do I set that?
a = [ab, cd, ef, gh, hi, jk] a.each do |i| #some stuff end
How does each work in Ruby? each is just another method on an object. That means that if you want to iterate over an array with each , you're calling the each method on that array object. It takes a list as it's first argument and a block as the second argument.
Array#each returns the [array] object it was invoked upon: the result of the block is discarded. Thus if there are no icky side-effects to the original array then nothing will have changed.
The each() is an inbuilt method in Ruby iterates over every element in the range. Parameters: The function accepts a block which specifies the way in which the elements are iterated. Return Value: It returns every elements in the range.
Another, possibly more direct and readable possibility is to use Array#drop
:
a.drop(3).each do |i| # do something with item i end
Now this really shines if combined with other methods inherited from Enumerable
, so chances are there's a better alternative to your imperative each
loop. Say you want to filter the extracted slice and transform it afterwards:
a = [0,1,2,3,4,5,6,7] a.drop(3).select(&:even?).map { |x| x * 2 } # => [8, 12]
Or say you want to print a list of all the values:
a = ["1", "2", "3", "4", "5"] puts a.drop(3).join("\n")
Output:
4 5
These features inherited from functional programming are what makes Ruby so strong :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With