Eval. get the console result into a variable

Hi,

The kernel methods "print", "puts" etc. actually call $stdout.write and
$stdout.puts. So you could simply create your own object with a write
and puts method and (temporarily) change $stdout to this object:

class OutputCollector

  attr_reader :content

  def write x
    @content += x.to_s
  end

  def puts x
    write x.to_s + "\n"
  end

  def initialize
    @content = ''
  end

end

# this changes $output to an instance of OutputCollector, executes the
block
# (all output will be written to the OutputCollector), changes $stdout
# back to the default value (given by STDOUT) and returns the collected
output
def catch_output
  coll = OutputCollector.new
  $stdout = coll
  yield
  $stdout = STDOUT
  coll.content
end

caught = catch_output do
  print 'abc'
  print 123
end

# show collected output
p caught

···

--
Posted via http://www.ruby-forum.com/.