String-based class that converts all replacements to concats in Ruby?

64 Views Asked by At

I am using open4::background to open a process on the shell. open4::background allows me to use any class that implements <<, each, read, or to_s as a handle to stdx.

I am currently using a String, but every time a write occurs on stdout, it replaces the old value. Is there a simple class I can use to make new write append instead of replace, considering the acceptance of any class that implements certain string-like functions?

I am new to Ruby and I am just hoping to plug this part in. If anyone can contribute or point me to a simple existing class for this I'd appreciate it.

There is a thread explaining this with a sample implentation here: http://www.ruby-forum.com/topic/151316 but I think that is a bit too complex for what I'm looking to do now. As a Ruby n00b, I'd feel more comfortable if someone else could massage that sample for me.

Thanks.

EDIT:

Per Phrogz's request, here is what I want to be able to do:

app_str = AppendedString
app_str = 'jeff'
app_str = 'walls'
puts app_str
# should display "jeffwalls"
2

There are 2 best solutions below

0
Phrogz On BEST ANSWER

What you want is to use StringIO to capture all the contents as a string for you.

(As @John says, repeated assignment you can't catch, but if you just want to accumulate all the values created by << then this will do it.)

0
John Feminella On
app_str = AppendedString
app_str = 'jeff'
app_str = 'walls'

This would require overriding the assignment operator. Unfortunately, Ruby doesn't permit overriding the assignment operator.