pretty print to a file in ruby

codeObserver picture codeObserver · Feb 10, 2012 · Viewed 11.4k times · Source

I am trying to pretty print a hash to a file.

I tried unix redirects [added different flags to it incrementally] :

`echo #{pp  mymap} | tee summary.out 2>&1`

and File IO

 my_file = File.new(@dir_+"/myfile.out",'w+')          
 my_file.puts `#{pp get_submap_from_final(all_mapping_file,final_map)}`

It always prints to console and doesnt write to a file.

Also there has to be an easier way to write to file in one line in ruby ? instead of doing File.new and then writing to a file ?

Answer

Huy Le picture Huy Le · Apr 7, 2012
require 'pp'

File.open("test.txt","w") do |f|
  PP.pp(self,f)
end