1

Does ruby have a native bidirectional string buffer class? I'd like to be able to do something like this:

buf = Buffer.new

Thread.new do
  while true
    # do some work
    buf << result
  end

  buf.close
end

Thread.new do
  until buf.eof?
    result = buf.readline
    # do some work
  end
end

StringIO supports either reading or writing, but not both. If I initialize a new one and write to it, then try to read from it, I won't get anything. Is there any way to get a plain old communication stream like this that doesn't require using mkfifo or something?

xanderflood
  • 826
  • 2
  • 12
  • 22
  • Possible duplicate: https://stackoverflow.com/questions/10045693/how-to-communicate-with-threads-in-ruby – Casper May 20 '18 at 23:46
  • Passing in-memory object back and forth is one thing, but I need to expose a standard Ruby stream interface on both ends with the usual read/write methods. Writing a wrapper around a queue is an option, but it seems like something that might be in the stdlib somewhere – xanderflood May 20 '18 at 23:48

1 Answers1

7

StringIO supports either reading or writing, but not both.

You can read from StringIO object you've just written to, just call rewind on your object.

I think you're looking after IO::pipe.

Artem Ignatiev
  • 331
  • 2
  • 6
  • I'll check out `IO::pipe`. StringIO will automatically rewind when you update the underlying string, but rewinding isn't what I want, since then the read would start over after every write – xanderflood May 20 '18 at 23:49
  • 1
    Sweet, `pipe` seems to be exactly what I need! – xanderflood May 20 '18 at 23:50