2011-06-28 34 views

回答

25

標準庫中包含的PP(以下簡稱 「漂亮打印」),其格式結構比標準好得多紅寶石檢查:

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

您需要require 'pp'位於源文件的頂部,然後才能使用它,然後在代碼中將p obj替換爲pp obj

我發現它特別適用於哈希和數組!

+1

PP還會將pretty_inspect()添加到內核模塊,所以你可以簡單地用它來替換調用inspect()。 – tjbp

5

除了'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 
+1

我最喜歡這個解決方案。使用rails控制檯時,我甚至不需要'yaml'。感謝發佈 –

0

這將工作,很好看:)

在你的Gemfile:

group :development do 
    gem 'table_print', '~> 1.5.3' 
end 
在你看來

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

像@tjbp說,只需簡單地使用pretty_inspect()而不是inspect()

它會給你很好的換行符和縮進