HomeHome ArchiveArchive

A RingBuffer in Ruby

I needed a ring buffer in Ruby, and since a web search didn’t yield anything I did it myself. Here you go, use as you wish:


Simple RingBuffer implementation
================================

see class RingBufferTest below for usage examples
=================================================

class RingBuffer \< Array

alias\_method :array\_push, :push
 alias\_method :array\_element, :[]

def initialize( size )
 @ring\_size = size
 super( size )
 end

def push( element )
 if length == @ring\_size
 shift \# loose element
 end
 array\_push element
 end

\# Access elements in the RingBuffer
 \#
 \# offset will be typically negative!
 \#
 def [](offset%20=%200)
 return self.array\_element( - 1 + offset )
 end
end

Usage example and unit test for the Ring Buffer
===============================================

require 'test/unit'
class RingBufferTest \< Test::Unit::TestCase

\# Usage example (and test)
 def test\_ring\_buffer

    rb = RingBuffer.new 2               # create RingBuffer with 2 elements

    rb.push 'Apple'                     # put 'Apple' into RingBuffer
    rb.push 'Pear'
    assert( rb[] == 'Pear' )            # the most recent element in the RingBuffer
                                        # is the 'Pear'

    assert( rb[0] == 'Pear' )           # same as before

    assert( rb[-1] == 'Apple' )         # get the second most recent element - it
                                        # shold be 'Apple'

    rb.push 'Mango'
    assert( rb == ['Pear', 'Mango'] )   # the 'Mango' has pushed the 'Apple' out of
                                        # the RingBuffer

end
end