Automatic counter in Ruby for each?

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

    If blahs is a class that mixes in Enumerable, you should be able to do this:

    blahs.each_with_index do |blah, i|
      puts("#{i} #{blah}")
    end
    

提交回复
热议问题