Automatic counter in Ruby for each?

前端 未结 8 1299
孤街浪徒
孤街浪徒 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:23

    If you don't have the new version of each_with_index, you can use the zip method to pair indexes with elements:

    blahs = %w{one two three four five}
    puts (1..blahs.length).zip(blahs).map{|pair|'%s %s' % pair}
    

    which produces:

    1 one
    2 two
    3 three
    4 four
    5 five
    

提交回复
热议问题