How to capture standart output to variable?


#1

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


#2

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 |
| >> |
±---------------------------------------------+


#3

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


#4

7stud – wrote:

You can send output to a string:

require “stringio”
. . .

Do this with “stringio” :wink:

±----------------------------------------------+
| >> 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 |
| >> |
±----------------------------------------------+