Forum: Ruby How to capture standart output to variable?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ce51aadca53420ecadd9108f14cdc096?d=identicon&s=25 Maxim Zhukov (rkdwv)
on 2009-02-08 21:08
How to capture output of this code to variable to send it to iconv?
(Just like ob_start() in PHP)

# ???
p ["utf-8 string",[123,321],"another string"]
# ???
puts Iconv.conv("866","UTF-8",captured_output) # because of windows
console
46a8ebdfabc2485407f89a2db5bdafb7?d=identicon&s=25 Igor Pirnovar (rooby)
on 2009-02-08 22:48
Maxim Zhukov wrote:
> How to capture output of this code to variable to send it to iconv?
> (Just like ob_start() in PHP)
>
> # ???
> p ["utf-8 string",[123,321],"another string"]
> # ???
> puts Iconv.conv("866","UTF-8",captured_output) # because of windows
> console

This irb example may help:
  +----------------------------------------------+
  | >> pipe = IO.popen("echo 'drop him a line'") |
  | => #<IO:0xb7a7b450>                          |
  | >> capture = pipe.read                       |
  | => "drop him a line\n"                       |
  | >> puts capture                              |
  | drop him a line                              |
  | => nil                                       |
  | >>                                           |
  +----------------------------------------------+
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2009-02-08 23:13
Maxim Zhukov wrote:
> How to capture output of this code to variable to send it to iconv?
> (Just like ob_start() in PHP)
>
> # ???
> p ["utf-8 string",[123,321],"another string"]
> # ???
> puts Iconv.conv("866","UTF-8",captured_output) # because of windows
> console

You can send output to a string:

require "stringio"

strio = StringIO.new
strio.write("hello world")
strio.rewind()
puts strio.read()

old_out = $stdout
$stdout = strio

puts " goodbye"
$stdout = old_out

strio.rewind()
puts strio.read()

--output:--
hello world
hello world goodbye
46a8ebdfabc2485407f89a2db5bdafb7?d=identicon&s=25 Igor Pirnovar (rooby)
on 2009-02-09 23:00
7stud -- wrote:

> You can send output to a string:
>
> require "stringio"
> . . .

Do this with "stringio" ;)

  +-----------------------------------------------+
  | >> pipe = IO.popen("/usr/games/fortune")      |
  | => #<IO:0xb7a6f588>                           |
  | >> capture = pipe.read                        |
  | => "You have taken yourself too seriously.\n" |
  | >> puts capture                               |
  | You have taken yourself too seriously.        |
  | => nil                                        |
  | >>                                            |
  +-----------------------------------------------+
This topic is locked and can not be replied to.