Ruby inspect方法以及其與to_s的區別:
[www.linuxidc.com @linuxidc ~]$ irb
1.9.3p194 :001 > class Dog
1.9.3p194 :002?> def say
1.9.3p194 :003?> puts "woof!"
1.9.3p194 :004?> end
1.9.3p194 :005?> end
=> nil
1.9.3p194 :006 > a = Dog.new
=> #<Dog:0x000000016dfff0>
1.9.3p194 :007 > a
=> #<Dog:0x000000016dfff0>
當直接查看對象a時,就會出現#<Dog:0x000000016dfff0> 這樣難懂的信息,其實這是一個預設的行為,我們可以隨意改變,只要為其加上inspect方法,就會返回以合理方式描述對象的字符串,包括對象以及所有實例變量的狀態。
1.9.3p194 :001 > class Dog
1.9.3p194 :002?> def inspect
1.9.3p194 :003?> "inspect"
1.9.3p194 :004?> end
1.9.3p194 :005?> def to_s
1.9.3p194 :006?> "to_s"
1.9.3p194 :007?> end
1.9.3p194 :008?> end
=> nil
1.9.3p194 :009 > a = Dog.new
=> inspect
1.9.3p194 :010 > a
=> inspect
1.9.3p194 :011 > puts a
to_s
=> nil
1.9.3p194 :012 > print
print printf
1.9.3p194 :012 > print a
to_s => nil
1.9.3p194 :013 > p a
inspect
=> inspect
inspect和to_s的區別就是
puts obj ==> puts obj.to_s
p obj ==> puts obj.inspect