By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,369 Members | 1,147 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,369 IT Pros & Developers. It's quick & easy.

read, write and seek method in ring buffer class

P: 1
Could any body help me with creating a ring buffer class using a string. use memory circular buffer not an IO buffer. just read, write and seek method. Read method should take anumber and return the string. write method should take a string. seek should take a number and return nuthing. use three member variables a buffer itself as a string, read_position, write_position. use >>, << methods.

I have tried this code but i need full functionality. May be you can understand the functionality by the below code

<code>
class RingBuffer

# Instanciate a ring buffer of the given size.
# The buffer will contain at most +size+ elements

def initialize(size)

# initialize the max

@max = size

# initialize the buffer array

@buffer = Array.new(size)

# initialize the read position

@read_position = read_position

# initialize the write position

@write_position = write_position

end

#
# Method to clear the buffer
#

def clear

@buffer = []

end

#
# method call to read the contents in a buffer
#

def read(read_position)

# is read position is greater than the maximum

if @read_position > @max

# if so

raise "Illeagal Read Position, the value is greater than the maximum value of buffer"

# is read position is lesser than the minimm value

if @read_position < -1

# if so

raise " Illeagal Read Position, the value is less than minimum"

end

end

# read the buffer value

str = @buffer[read_position].to_s

# return the string

return str

end


#
# method call to write contents in a buffer
#

def write(value)


# shift the buffer

@buffer.shift

# append the value at the end

@buffer << value

end


#
# method call to convert buffer array
#

def to_a

# return the buffer element

return @buffer.dup

end

#
# method call to convert to string
#

def to_s

# initialize the str

str = ""

# each value in the buffer is converted to string

@buffer.each { |entry|
str << entry.to_s << "\n"

}

# return the string elements

return str

end

#
# method call to seek position
#

def seek




end

end
</code>

Thanks in advance
Nov 21 '07 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.