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
Here's an expansion to the post above to also to pretty print json output to a file.
require "pp"
require "json"
class File
def pp(*objs)
objs.each {|obj|
PP.pp(obj, self)
}
objs.size <= 1 ? objs.first : objs
end
def jj(*objs)
objs.each {|obj|
obj = JSON.parse(obj.to_json)
self.puts JSON.pretty_generate(obj)
}
objs.size <= 1 ? objs.first : objs
end
end
test_object = { :name => { first: "Christopher", last: "Mullins" }, :grades => [ "English" => "B+", "Algebra" => "A+" ] }
test_json_object = JSON.parse(test_object.to_json)
File.open("log/object_dump.txt", "w") do |file|
file.pp(test_object)
end
File.open("log/json_dump.txt", "w") do |file|
file.jj(test_json_object)
end
require 'pp'
File.open("test.txt","w") do |f|
PP.pp(self,f)
end
The use of backticks here is perplexing since those are used for executing shell commands.
What you probably mean is:
File.open(@dir_+"/myfile.out",'w+') do |f|
f.write(pp(get_submap_from_final(all_mapping_file,final_map)))
end
The pp
method always writes to the console so you might see it and still have it written.
require 'pp'
class File
def pp(*objs)
objs.each {|obj|
PP.pp(obj, self)
}
objs.size <= 1 ? objs.first : objs
end
end
File.open('output','w') do |file|
file.pp mymap
end
Doing something similar to what Edu suggested and How do I redirect stderr and stdout to file for a Ruby script? helped.
Here is how the new code is similar to:
$stdout.reopen(@dir_+"/my_file.out",'w+')
puts "All metrics are:"
pp final_map
$stdout=STDOUT
Would still be interested to know why redirection operators > , and 2>&1 in back-ticks doesn't work
What about (not using pp directly):
File.open("myfile.out","w+") do |f|
f.puts mymap.inspect
end
Or even redirect stdout for the file
file = File.open("myfile.out", "w+)
old_stdout = STDOUT
$stdout = STDOUT = file
pp get_submap_from_final(all_mapping_file,final_map)
$stdout = STDOUT = old_stdout