Hello,
I need a simple way to redirect output from methods defined
in a module, using puts.
Example:
module Foo
def test
puts 'Hello World!'
end
end
class Bar
def initialize
@string = ''
end
def add(this_text)
@string << this_text
end
end
In the above example, I would like to be able to redirect the
puts output from the method test, into a new instance of Bar.new
@string.
I assume it can somehow be done via re-assigning stdout, and
then restoring it afterwards, using some kind of IO Object
possibly. I have been reading some blog entries but I still
do not understand it - I can easily redirect into a file,
but I do not understand how to redirect into an instance
variable of a given class.
What exactly do you want to do? Are you writing the module Foo yourself
or are you working with a library? Who or what calls Foo#test, and what
do you want to happen with the newly created object of class Bar?
How about just modifying the method test in Foo?
module Foo
def test
Bar.new.add ‘Hello World!’
end
end
Or do you mean something like this?
module Foo
def test
puts ‘Hello World!’
end
end
class Bar
def initialize
@string = ‘’
end
def add(this_text)
@string << this_text
self
end
end
class Test
include Foo
end
module Foo
def puts(*x)
super
Bar.new.add x[0]
end
end
puts Test.new.test
This print “Hello World!” and returns a new Bar object with “Hello
World!”.
You can capture stdout, see here
ruby - How can I capture STDOUT to a string? - Stack Overflow.
If you’ve got some external command you want to run, you can capture
stdout like this:
IO.popen(“echo hello world”) do |io|
puts io.read
end