Automatic counter in Ruby for each?

前端 未结 8 1292
孤街浪徒
孤街浪徒 2020-11-29 23:02

I want to use a for-each and a counter:

i=0
for blah in blahs
    puts i.to_s + \" \" + blah
    i+=1
end

Is there a better way to do it?

8条回答
  •  孤城傲影
    2020-11-29 23:30

    As people have said, you can use

    each_with_index
    

    but if you want indices with an iterator different to "each" (for example, if you want to map with an index or something like that) you can concatenate enumerators with the each_with_index method, or simply use with_index:

    blahs.each_with_index.map { |blah, index| something(blah, index)}
    
    blahs.map.with_index { |blah, index| something(blah, index) }
    

    This is something you can do from ruby 1.8.7 and 1.9.

提交回复
热议问题