Skip to content

Instantly share code, notes, and snippets.

@julik
Last active January 15, 2019 20:32
Show Gist options
  • Save julik/a4c0b88abc17922f4f2a1a01a6bba530 to your computer and use it in GitHub Desktop.
Save julik/a4c0b88abc17922f4f2a1a01a6bba530 to your computer and use it in GitHub Desktop.
A small ring buffer implementation in Ruby
# A ring buffer enumerable object
class Ring
include Enumerable
def initialize(size)
@array = Array.new(size)
@pos = 0
end
def pos
@pos
end
def each
previous_pos = @pos
@array.length.times { yield(self.next) }
self
ensure
@pos = previous_pos
end
def <<(value)
@array[@pos] = value
@pos = (@pos + 1) % @array.length
self
end
def next
@array[@pos].tap do
@pos = (@pos + 1) % @array.length
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment