Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby each_with_index offset

Tags:

iteration

ruby

Can I define the offset of the index in the each_with_index loop iterator? My straight forward attempt failed:

some_array.each_with_index{|item, index = 1| some_func(item, index) } 

Edit:

Clarification: I don't want an array offset I want that the index within the each_with_index doesn't start from 0 but e.g. 1.

like image 512
Mark Avatar asked Apr 13 '11 08:04

Mark


2 Answers

Actually, Enumerator#with_index receives offset as an optional parameter:

[:foo, :bar, :baz].to_enum.with_index(1).each do |elem, i|   puts "#{i}: #{elem}" end 

outputs:

1: foo 2: bar 3: baz 

BTW, I think it is there only in 1.9.2.

like image 83
Mladen Jablanović Avatar answered Sep 21 '22 13:09

Mladen Jablanović


The following is succinct, using Ruby's Enumerator class.

[:foo, :bar, :baz].each.with_index(1) do |elem, i|     puts "#{i}: #{elem}" end 

output

1: foo 2: bar 3: baz 

Array#each returns an enumerator, and calling Enumerator#with_index returns another enumerator, to which a block is passed.

like image 29
Zack Xu Avatar answered Sep 20 '22 13:09

Zack Xu