# ========================================= # ringbuf.rb # # Ringbuffer Class. # ========================================= class RingBuffer # Instanciate a ring buffer of the given size. # The buffer will contain at most +size+ elements def initialize(size) @max = size @buffer = [] end # Add an element at the end of the buffer # If size is exceeded, the first element is dropped def push(line) @buffer.push(line) if @buffer.size > @max @buffer.shift end end # Resets buffer def clear @buffer=[] end # Return the content as Array def to_a return @buffer.dup end # Return content as a string containing each entry # on a single line def to_s str = "" @buffer.each { |entry| str << entry << "\n" } return str end # Call the closure block on each element in the buffer def each(&block) @buffer.each(&block) end end