pp
के आउटपुट को कैप्चर करने के लिए यह nice 'n simple तरीका है:
require 'pp'
asdf = {'a' => 1, :b => 2, 'c' => %w[ho daddy]}
foo = PP.pp(asdf, '')
puts foo
=> {"a"=>1, :b=>2, "c"=>["ho", "daddy"]}
कैप्चर STDOUT, जो डिफ़ॉल्ट पर pp
पिग्गीबैक तरह puts
और print
द्वारा और है कि चीजें इस्तेमाल किया चैनल, एक थोड़ा और अधिक जटिल है:
require 'pp'
require 'stringio'
asdf = {'a' => 1, :b => 2, 'c' => %w[ho daddy]}
puts 'Writing to STDOUT...'
pp asdf
# remember the old STDOUT stream...
old_stdout = $stdout
# ...and create a new stream that writes to a string.
captured_stdio = StringIO.new('', 'w')
$stdout = captured_stdio
# This is all captured...
puts 'Capturing to buffer...'
pp asdf
# reset STDOUT
$stdout = old_stdout
puts 'Capturing off...'
# show what we got...
puts captured_stdio.string
और क्या छपा था:
Writing to STDOUT...
{"a"=>1, :b=>2, "c"=>["ho", "daddy"]}
Capturing off...
Capturing to buffer...
{"a"=>1, :b=>2, "c"=>["ho", "daddy"]}
उपरोक्त अंतिम दो पंक्तियों को captured_stdio
में सामान्य $stdout
चैनल के लिए प्रतिस्थापित करके संग्रहीत किया गया था। कुछ भी लिखा गया है (एसटीडीओयूटी क्या होगा) संग्रहित हो गया। मूल चैनल में वापस स्वैपिंग ने सामान्य प्रिंटिंग बहाल की, और captured_stdio
पर लिखे जाने से कुछ और रोक दिया।
स्रोत
2013-03-08 01:53:11
+1 अच्छा प्रश्न। –
संभावित डुप्लिकेट [STDOUT के बजाय एक चर के लिए सुंदर प्रिंट कैसे करें?] (Http://stackoverflow.com/questions/14127375/how-to-pretty-print-to-a-variable-instead-of-stdout) – akostadinov