Ruby检查可读性?

有没有办法让检查输出更具可读性?

在Perl中,有Data::Dumper ,它使输出更容易阅读。

ruby标准库包含PP(“Pretty Print”的缩写),它比标准检查更好地格式化结构:

http://www.ruby-doc.org/stdlib/libdoc/pp/rdoc/index.html

在使用之前,您require 'pp'在源文件的顶部require 'pp' ,然后在代码中将pp obj替换为pp obj

我发现它特别适用于哈希和数组!

试试awesome_print: http ://www.rubyinside.com/awesome_print-a-new-pretty-printer-for-your-ruby-objects-3208.html

除了’pp’解决方案,yaml可能是一个解决方案。

尝试:

 require 'yaml' puts [1,2,3=>'three'].to_yaml 

你得到:

 --- - 1 - 2 - 3: three 

还有一个完全不同的方法:如果您遇到特定类的检查问题,请编写自己的检查代码

例:

 class MyTest def initialize() @created = Time.now end def inspect() "Hi, I'm the objected created at #{@created}. That's #{Time.now - @created} seconds ago" end end x = MyTest.new sleep 5 puts x.inspect 

你得到

 Hi, I'm the objected created at 2011-06-28 12:48:38 +0100. That's 5.0 seconds ago 

比如@tjbp说,只需使用pretty_inspect()而不是inspect()

它会给你很好的换行和缩进

这将工作,看起来很棒:)

在你的gemfile中:

 group :development do gem 'table_print', '~> 1.5.3' end 

在你看来:

 
 <%= TablePrint::Printer.new(@users, []).table_print %>