How to capture standart output to variable?

M

Maxim Zhukov

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
 
I

Igor Pirnovar

Maxim said:
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 |
| >> |
+----------------------------------------------+
 
7

7stud --

Maxim said:
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
 
I

Igor Pirnovar

7stud said:
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 |
| >> |
+-----------------------------------------------+
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top