From: Rob Biedenharn Date: 2010-10-04T04:19:59+09:00 Subject: Re: Puts to stream? On Oct 3, 2010, at 2:54 PM, Terry Michaels wrote: > I've got simple statements like so: > > puts "hi" > puts "there" > puts name > > Wanted to adjust it to write to IO object (a string) instead of > stdout. > This is the kind of construction I'd like to use: > > my_out = String.new > puts my_out "hi" > puts my_out "there" > puts my_out name > > But apparently that doesn't work. This seems to work > > my_out << "hi" << "\n" > my_out << "there" << "\n" > my_out << name << "\n" > > The lame part of that, though, is that it does not do the whole "check > if there is an end-line and add one if there isn't" magic, so I have > to > manually specify the newline if I want one. I tried > > my_out.puts "hi" > > But evidently that does the exact opposite of want I want. > -- > Posted via http://www.ruby-forum.com/. > In addition to Quintus, here's a bit more depending on how far you're looking to go: irb> puts "hi" hi => nil irb> require 'stringio' => true irb> my_out = StringIO.new('') => # irb> my_out.puts "hi" => nil irb> my_out.string => "hi\n" So you can explicitly use puts on the StringIO instance. If you want to implicitly target your StringIO, you can: irb> begin ?> saved_stdout = $stdout irb> $stdout = my_out irb> puts "there" irb> ensure ?> $stdout = saved_stdout irb> end => nil irb> my_out.string => "hi\nthere\n" Note that the ensure block puts $stdout back to where it started. -Rob Rob Biedenharn Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/ rab@GaslightSoftware.com http://GaslightSoftware.com/