Note first that all of this applies to each pair of “short” (e.g. to_s
/to_i
/to_a
/to_h
) vs. “long” (e.g. to_str
/to_int
/to_ary
/to_hash
) coercion methods in Ruby (for their respective types) as they all have the same semantics.
They have different meanings. You should not implement to_str
unless your object acts like a string, rather than just being representable by a string. The only core class that implements to_str
is String itself.
From Programming Ruby (quoted from this blog post, which is worth reading all of):
[to_i
and to_s
] are not particularly strict: if an object has some kind of decent representation as a string, for example, it will probably have a to_s
method… [to_int
and to_str
] are strict conversion functions: you implement them only if [your] object can naturally be used every place a string or an integer could be used.
Older Ruby documentation from the Pickaxe has this to say:
Unlike to_s
, which is supported by almost all classes, to_str
is normally implemented only by those classes that act like strings.
For example, in addition to Integer, both Float & Numeric implement to_int
(to_i
's equivalent of to_str
) because both of them can readily substituted for an Integer (they are all actually numbers). Unless your class has a similarly tight relationship with String, you should not implement to_str
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…