Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - each starting offset

Tags:

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 
like image 886
Majoris Avatar asked May 01 '12 10:05

Majoris


People also ask

Is it possible to use each and each in Ruby?

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.

What does each return in Ruby?

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.

What is each method in Ruby?

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.


1 Answers

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 :)

like image 120
Niklas B. Avatar answered Oct 06 '22 16:10

Niklas B.