Skip to content

Instantly share code, notes, and snippets.

@jhjguxin
Forked from eerohele/ringbuffer.rb
Created October 29, 2018 12:00
Show Gist options
  • Save jhjguxin/b1f21748658638a5e4a8779f19fe7e2e to your computer and use it in GitHub Desktop.
Save jhjguxin/b1f21748658638a5e4a8779f19fe7e2e to your computer and use it in GitHub Desktop.
A simple ring buffer for Ruby.
class RingBuffer < Array
attr_reader :max_size
def initialize(max_size, enum = nil)
@max_size = max_size
enum.each { |e| self << e } if enum
end
def <<(el)
if self.size < @max_size || @max_size.nil?
super
else
self.shift
self.push(el)
end
end
alias :push :<<
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment