to_s 是显式的转换帮助器,用于将值从一种类型转换为另一种类型。 to_str 是具有相同目的的隐式转换帮助器。区别在于,前者将始终返回字符串,而后者所作用的值与我们正在转换的类型不同,则将导致错误或数据丢失。
当对象的行为类似于类型时,Ruby只会返回一个值。在使用隐式转换助手时,Ruby非常严格,以确保该值的行为类似于我们想要的类型。
irb> [1, 2].to_s => "[1, 2]" irb> [1, 2].to_str NoMethodError: undefined method `to_str` for [1, 2]:Array Did you mean? to_s irb> :name.to_s => "name" irb> :name.to_str NoMethodError: undefined method `to_str` for :name:Symbol Did you mean? to_s