Skip to content

Instantly share code, notes, and snippets.

@paul
Created Sep 18, 2015
Embed
What would you like to do?
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