From: WATANABE Hirofumi Date: 2002-11-15T12:48:56+09:00 Subject: Re: Howot redirect STDOUT to a string within a script? Phil Tomson writes: > Let's say I've got some strings with Ruby code to be eval'ed, like: > > evalstr = 'puts "this is the string"' > > and let's say I want to get the part that's sent to STDOUT (by puts) and > capture it in a string, like so: > > outputStr = eval evalstr #=> outputStr = "this is the string" > > I suspect I could do this by redefining 'puts', but is there a way of > doing it so that puts is only redefined within the context of the eval? Ruby 1.7 has StringIO. require 'stringio' def redirect orig_defout = $defout $defout = StringIO.new yield $defout.string ensure $defout = orig_defout end evalstr = 'puts "this is the string"' outputStr = redirect { eval evalstr } p outputStr If you want to use StringIO in Ruby 1.6, check Ruby Shim: http://www.ruby-lang.org/en/raa-list.rhtml?name=Ruby+Shim+for+1.6 or MoonWolf's StringIO: //http://www.moonwolf.com/ruby/archive/stringio01.zip -- eban