fork download
  1. # returns an enumerator which executes block on each nth iteration
  2. def on_nth_run_enum freq, &block
  3. Enumerator.new do |yielder|
  4. loop do
  5. freq.times do
  6. yielder.yield
  7. end
  8. block.call
  9. end
  10. end
  11. end
  12.  
  13. # an object of this class will execute given block
  14. # every nth time "run" method has been invoked
  15. class OccasionalRunner
  16. def initialize freq, &block
  17. @freq = freq
  18. @block = block
  19. @counter = 0
  20. end
  21.  
  22. def run
  23. @counter = (@counter + 1) % @freq
  24. @block.call if @counter == 0
  25. end
  26. end
  27.  
  28. # returns lamda which will execute given block
  29. # every nth time being called
  30. def on_nth_run_fun freq, &block
  31. counter = 0
  32. -> {
  33. counter = (counter + 1) % freq
  34. block.call if counter == 0
  35. }
  36. end
  37.  
  38. janitor_enum = on_nth_run_enum 3 do
  39. puts 'cleanup - enumerable way'
  40. end
  41.  
  42. janitor_oo = OccasionalRunner.new 3 do
  43. puts 'cleanup - OO way'
  44. end
  45.  
  46. janitor_fun = on_nth_run_fun 3 do
  47. puts 'cleanup - functional style'
  48. end
  49.  
  50. (1..10).each do |i|
  51. puts i
  52. janitor_enum.next
  53. janitor_oo.run
  54. janitor_fun.call
  55. end
Success #stdin #stdout 0s 4868KB
stdin
Standard input is empty
stdout
1
2
3
cleanup - OO way
cleanup - functional style
4
cleanup - enumerable way
5
6
cleanup - OO way
cleanup - functional style
7
cleanup - enumerable way
8
9
cleanup - OO way
cleanup - functional style
10
cleanup - enumerable way