Search code examples
ruby

Why is Pathname not considered a string (or when is it okay to add a to_str method to a class)?


There was a bug report Pathname#to_str doesn't appear to work anymore. Having to_str in Pathname would let you use Pathname anywhere you use a string, eg with Dir, system, etc. However the bug report was rejected, and it appears from a commit message that the to_str method was deliberately removed.

I don't understand this - Pathname can be loselessly converted to a String and back, and it would be very convenient when working with APIs that don't use Pathname.

So why is having to_str not appropriate for Pathname, and when is to_str okay to use?


Solution

  • Here's an article that attempts to answer your question but, in my opinion, doesn't really succeed.

    Around the same time Pathname#to_str was removed Exception#to_str was removed as well--clearly Matz was trying to draw a line in the sand at this time between "stringlike" and "non-stringlike" classes. The Exception change makes sense--an Exception cannot, to use your words, "be losslessly converted to a String and back," because an Exception object contains lots of other information--the stack trace in particular--that would be lost in that conversion.

    I can only guess but I'd wager that Matz felt the same way about Pathname, though it's unclear why. Even the documentation (1.9.3) at one point, says (under "Core methods"), "These methods are effectively manipulating a String, because that’s all a path is." Several sources I've found--in addition to the one @MarkThomas cites--use Pathname as an example of a class for which to_str does make sense, probably taking a cue from Hal Fulton's The Ruby Way.

    I guess this isn't a very satisfactory answer. If you really want to know you may have to ask on Ruby-Talk or Ruby-Core. You could try asking Matz on X, but he seems to converse exclusively in Japanese. Wycats and Jeremy Daer may have some more insight, though, and seem pretty accessible. Good luck!

    P.S. This article has a section "Technical explanation of to_str and friends" that I found interesting, but it doesn't do any better a job of answering your question.