Skip to content

Instantly share code, notes, and snippets.

@knu
Created May 10, 2009 08:38
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 knu/109550 to your computer and use it in GitHub Desktop.
Save knu/109550 to your computer and use it in GitHub Desktop.
class Enumerator
class Buffer
attr_accessor :status
def initialize(yielder, initial_status = nil)
@buffer = []
@yielder = yielder
@status = initial_status
end
def push(item)
@buffer.push(item)
end
alias << push
def pop
@buffer.pop
end
def clear
@buffer.clear
self
end
def empty?
@buffer.empty?
end
def size
@buffer.size
end
def flush
return false if @buffer.empty?
@yielder.yield(@buffer)
@buffer = []
true
end
end
end
module Enumerable
def buffer(initial_status = nil, &block)
Enumerator.new { |yielder|
buffer = Enumerator::Buffer.new(yielder, initial_status)
each { |*args|
case args.size
when 0
block.call(buffer)
when 1
block.call(args.first, buffer)
else
block.call(args, buffer)
end
}
buffer.flush
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment