I'm learning Ruby and I've seen a couple of methods that are confusing me a bit, particularly
Note first that all of this applies to each pair of “short” (e.g.
to_h) vs. “long” (e.g.
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_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_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:
to_s, which is supported by almost all classes,
to_stris normally implemented only by those classes that act like strings.
For example, in addition to Integer, both Float & Numeric implement
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