Ruby inspect方法以及其与to_s的区别:
[ @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