It’s Monday and it’s relatively early, so I apologize if this isn’t
worded too well.
Is there a clean way of pausing a loop/printing status every N
iterations? I often use ruby to examine log files in a one-off
fashion, and when dealing with files of 4-10 million lines, this is
the sort of thing that becomes important. Small files are, obviously,
not as big of a deal.
I know I can simply do this, but it doesn’t seem clean:
counter=0
n=100
foo.each do
|bar|
counter+=1
if (counter%n).zero?
sleep 0.1
end
counter=0
n=100
foo.each do
|bar|
counter+=1
if (counter%n).zero?
sleep 0.1
end
What’s wrong with it? I can only think that if foo allows
.each_with_index, you could avoid the counter initialization and
addition. Can’t think of anything else.
module Enumerable
def paused_each n, sec, pause_after=true
counter = 0
self.each do |e|
yield e if pause_after
if (counter += 1) >= n
counter = 0
sleep sec
end
yield e unless pause_after
end
end
end
[1,2,3,4,5,6,7].paused_each(2,2) { |e| puts e }
puts
[1,2,3,4,5,6,7].paused_each(2,2,false) { |e| puts e }
It’s Monday and it’s relatively early, so I apologize if this isn’t
worded too well.
Is there a clean way of pausing a loop/printing status every N
iterations? I often use ruby to examine log files in a one-off
fashion, and when dealing with files of 4-10 million lines, this is
the sort of thing that becomes important. Small files are, obviously,
not as big of a deal.
Hum. Well those all work, but aren’t those basically similar to what
I’m already doing?
I was hoping to somehow have a handler that would inject the logic
into an existing loop.
Oh well.
Thanks,
Kyle
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.