我很好奇为什么当你在一个对象上调用“p”时为什么它调用 .to_s 方法但实际上并没有返回一个字符串。当您明确调用 .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"