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 = 0 )
    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