From: Robert Klemme Date: 2010-07-18T16:30:08+09:00 Subject: Re: Driving irb from IO.popen On 07/17/2010 06:43 PM, Jean-Julien Fleck wrote: > Hello Robert, > >> Note:<< is more efficient than += here. > > Yes. Bad habit on my side: I tend to find it more readable that way so > I don't use<< so often. I should rather use it more to find it easier > to read :o) > > Correct me if I'm wrong:<< will append to the existing String object > whereas += will create a brand new String object by concatenating the > two (the old version and what I want to add), Correct. > so it could be less > efficient if the string gets too long and/or if there are a lot of > line to append ? I don't think so. You have two cost factors: allocating the underlying memory to hold the sequence of characters (or bytes if you will) and the allocation of an object, registration with GC etc. The first cost factor needs to be paid regardless of variant used while the second costs factor is not incurred with the << version. Memory allocation overhead is usually kept low by using a smart algorithm for calculating the size of the next memory chunk to allocate so allocations become rarer with more append operations of identical sized strings. IMHO the version with the single read that slurps in everything is even more efficient because you loop in C and not in Ruby. (Note that Ruby's multithreading is not negatively affected; the single read does not block other threads.) >> Not a workaround but a solution: since you only want to collect the output >> of irb and do not need to react on it you can simply use a second thread >> that collects all the output. > > Thanks a lot, it works perfectly ! > > I don't need it now but as I have already been confronted to this > issue (finding workarounds as I had access to the other program and > could modify it), I'll ask anyway: how would you tackle the problem if > you did have to react to the output ? (just some hints would perfectly > please me) There is expect ("ri IO#expect"). Documentation is a tad sparse but there's likely more to find on the web. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/