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|

1 Answer 1

2

try this:

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

this example will start from fifth element.

Sign up to request clarification or add additional context in comments.

4 Comments

Well, that is not exactly what i need. I need the index to start with 1, index is used further in block.
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?
I guess the author just needs method_that_uses_index(index+1) :)
[1,2,3,4,5,6].drop(3).each_with_index {|e,i|p e;p i}is an alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.