Created
September 18, 2015 17:46
-
-
Save paul/d8a35c00035306bb7d90 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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