Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@Nimster

This comment has been minimized.

Copy link

@Nimster Nimster commented Nov 15, 2012

This has a major bug. << by default means "push", so
a = RingBuffer.new(3)
a << "first"
a << "second"
a << "third" # a == ["first", "second", "third"]
# but now
a << "fourth" # a == ["fourth", "first", "second"]

Where one would expect after the fourth insertion, a would contain ["second", "third", "fourth"]. This is consistent with a RingBuffer being a data structure for MRU access, i.e oldest elements should be overwritten.

@Nimster

This comment has been minimized.

Copy link

@Nimster Nimster commented Nov 15, 2012

I fixed this on my fork, https://gist.github.com/4078106

@eerohele

This comment has been minimized.

Copy link
Owner Author

@eerohele eerohele commented Jan 4, 2013

@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.

@captainpete

This comment has been minimized.

Copy link

@captainpete captainpete commented Feb 15, 2014

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