I’m learning Ruby and I’ve seen a couple of methods that are confusing me a bit, particularly to_s vs to_str (and similarly, to_i/to_int, to_a/to_ary, & to_h/to_hash). What I’ve read explains that the shorter form (e.g. to_s) are for explicit conversions while the longer form are for implicit conversions.
I don’t really understand how to_str would actually be used. Would something other than a String ever define to_str? Can you give a practical application for this method?
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_strunless your object acts like a string, rather than just being representable by a string. The only core class that implementsto_stris String itself.From Programming Ruby (quoted from this blog post, which is worth reading all of):
Older Ruby documentation from the Pickaxe has this to say:
For example, in addition to Integer, both Float & Numeric implement
to_int(to_i‘s equivalent ofto_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 implementto_str.