Last active
October 29, 2018 12:00
-
-
Save eerohele/1904422 to your computer and use it in GitHub Desktop.
A simple ring buffer for Ruby.
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
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 |
@Nimster: many thanks for pointing it out, fixed. I'm still very much a Ruby newbie, and certainly much more so when I originally created this Gist.
Also check out this threadsafe one http://git.io/8RZjeA
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I fixed this on my fork, https://gist.github.com/4078106