1

How can i specify which index to start from when using each_with_index on a collection in ruby 1.8.7?

collection.each_with_index do |element, index = 1|
  #do smth
end

Using it like this gives the following error:

syntax error, unexpected '=', expecting '|'
collection.each_with_index do |element, i = 1|
roman
  • 5,100
  • 14
  • 44
  • 77

1 Answers1

2

try this:

collection[4..-1].each_with_index do |element, index|
  #do smth
end

this example will start from fifth element.

alexkv
  • 5,144
  • 2
  • 21
  • 18
  • Well, that is not exactly what i need. I need the index to start with `1`, `index` is used further in block. – roman May 30 '12 at 12:18
  • Do I understand correctly? For example you have array ['a', 'b','c','d']. You want to start from element 'b'? Or you want to have first index for example 1 not 0? – alexkv May 30 '12 at 12:20
  • 1
    I guess the author just needs `method_that_uses_index(index+1)` :) – jdoe May 30 '12 at 12:25
  • `[1,2,3,4,5,6].drop(3).each_with_index {|e,i|p e;p i}`is an alternative. – steenslag May 30 '12 at 16:23