Kyle Schmitt <kyleaschmitt / gmail.com> writes:

> 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
>
> Thanks,
>        Kyle
> end

Maybe something like this?

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 }