3 回答

TA貢獻(xiàn)1788條經(jīng)驗 獲得超4個贊
p foo
打印foo.inspect
跟著一個新行,即,它打印的值inspect
代替to_s
,這是更適合的調(diào)試(因為可以例如告訴之間的差1
,"1"
并且"2\b1"
,它可以不打印時不inspect
)。

TA貢獻(xiàn)1869條經(jīng)驗 獲得超4個贊
同樣重要的是要注意puts對已to_s定義的類的“反應(yīng)” p不會。例如:
class T
def initialize(i)
@i = i
end
def to_s
@i.to_s
end
end
t = T.new 42
puts t => 42
p t => #<T:0xb7ecc8b0 @i=42>
這直接來自.inspect調(diào)用,但是在實踐中并不明顯。

TA貢獻(xiàn)1757條經(jīng)驗 獲得超7個贊
除了上述答案外,控制臺輸出中還有細(xì)微的差別-即是否存在逗號/引號引起來-這可能是有用的:
p "+++++"
>> "+++++"
puts "====="
>> =====
如果您想使用它們的近親print創(chuàng)建一個簡單的進(jìn)度欄,那么我發(fā)現(xiàn)這很有用:
array = [lots of objects to be processed]
array.size
>> 20
這給出了100%的進(jìn)度條:
puts "*" * array.size
>> ********************
這會在每次迭代中添加一個增量*:
array.each do |obj|
print "*"
obj.some_long_executing_process
end
# This increments nicely to give the dev some indication of progress / time until completion
>> ******
- 3 回答
- 0 關(guān)注
- 507 瀏覽
添加回答
舉報