pretty print to a file in ruby

后端 未结 7 777
甜味超标
甜味超标 2021-02-07 00:11

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          


        
7条回答
  •  感情败类
    2021-02-07 00:14

    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
    

提交回复
热议问题