开发者

How do I know what iteration I'm in when using the Integer.times method?

Let's say I have

some_value = 23

I use the Integer's times method to loop.

Inside the开发者_高级运维 iteration, is there an easy way, without keeping a counter, to see what iteration the loop is currently in?


Yes, just have your block accept an argument:

some_value.times{ |index| puts index }
#=> 0
#=> 1
#=> 2
#=> ...

or

some_value.times do |index|
  puts index
end
#=> 0
#=> 1
#=> 2
#=> ...


3.times do |i|
  puts i*100
end

In this way, you can replace 3 with any integer you like, and manipulate the index i in your looped calculations. My example will print the following, since the index starts from 0:

# output

0

100

200
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜