我很好奇为什么当你在一个对象上调用“p”时为什么它调用.to_s方法但实际上并没有返回一个String。当您明确调用.to_s时,它会以字符串形式输出。
1.9.3p194 :078 > class Test
1.9.3p194 :079?> def to_s
1.9.3p194 :080?> puts 'to string called'
1.9.3p194 :081?> "testing"
1.9.3p194 :082?> end
1.9.3p194 :083?> end
=> nil
1.9.3p194 :084 > x = Test.new
to string called
=> testing
1.9.3p194 :085 > x
to string called
=> testing
1.9.3p194 :086 > p x
to string called
testing
to string called
=> testing
1.9.3p194 :087 > p x.to_s
to string called
"testing"
=> "testing"
答案 0 :(得分:4)
p将传入的对象的字符串化表示写入标准输出。然后它返回自己。如果你想要p打印的字符串值,你可以使用inspect方法:
> a = p 233
233
> a.class # Fixnum
> 233.inspect # "233"