Skip to content

Instantly share code, notes, and snippets.

@paul
Created September 18, 2015 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paul/d8a35c00035306bb7d90 to your computer and use it in GitHub Desktop.
Save paul/d8a35c00035306bb7d90 to your computer and use it in GitHub Desktop.
module EveryNth
def every_nth(n)
Enumerator.new do |yielder|
with_index do |*a, i|
yielder.yield(*a)
yield i if (i+1) % n == 0
end
end
end
end
Enumerator.send(:include, EveryNth)
[1] pry(main)> 1000.times.every_nth(100) { |i| puts "Hello from #{i}" }.each { |n| nil }
Hello from 99
Hello from 199
Hello from 299
Hello from 399
Hello from 499
Hello from 599
Hello from 699
Hello from 799
Hello from 899
Hello from 999
=> 1000
Actual Use Case:
huge_mongo_collection.batch_size(100).every_nth(1000) { print_memory_usage }.each do |row|
# Do actual work here
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment