Last active
January 15, 2019 20:32
-
-
Save julik/a4c0b88abc17922f4f2a1a01a6bba530 to your computer and use it in GitHub Desktop.
A small ring buffer implementation in Ruby
This file contains hidden or 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
# 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