From: Aaron Patterson Date: 2009-10-03T02:22:42+09:00 Subject: Re: Rolling String Buffer needed On Oct 2, 2009, at 9:55 AM, Matt Brooks wrote: > I have constant ascii data streaming in, each message terminated with > \n, currently I look for something specific and throw away the other > stuff and then look for something specific and throw away the other > stuff...etc > > What I need now is a way to keep everything received exactly as is, > in a > rolling string buffer. So say the last 100 messages (a message to > me is > a whole string terminated with \n) which could be available at any > time > in a string variable, maybe called: last_100_messages > > And when I append another variable length message/line to this string > buffer that ends with a \n, I want the oldest message to go > away(specifically go into a text file), so ALL messages are > available in > a text file for later. > > > > > Problem is the append << method, puts the new lines on the end of the > string, I want the end of the string to always be the oldest message > that is about to be placed into a txt file that has all messages at > some > point. > > So in short, a rolling buffer that holds a specific amount of \n > terminated messages(100 strings terminated with \n's), not a specific > amount of data/bytes. Where the front of the string holds the most > recent addition to the rolling buffer, and where the end of the string > holds the message that is about to be added to a file. > > > > > Also if easier, an array where each element is one message would > work as > well, where array[0] is the most recent message. > > I have been looking at strio, but not sure how to use it in this > manner. I think you could just write a class that wraps up a list. Something like this: class MyBuff def initialize max_size, filename @max_size = max_size @list = [] @file = File.open(filename, 'wb') end def push string @list.push string while @list.length > @max_size @file.write @list.pop end end def [] i @list[i] end end --- Aaron Patterson http://tenderlovemaking.com