Implicit conversion doesn’t come up very often in ruby. It’s a duck-typed language, so as long as an object has the right instance methods defined, everything should be fine. Sometimes though, when you’re dealing with system libraries or linking with other languages, ruby really does need a way to convert your objects into fundamental types, like strings, hashes, and arrays.
Despite their similarity, did you know that there is a language-level difference between #to_s and #to_str?
- is a normal, but common, method used to show a string-representation of an object, nominally for diagnostic purposes.
- is meant for objects that can be used “as a string”. ie: “implicit conversion”
When I was first working on the Rakefile to build this blog, I was using Pathname all over the place. When you’re writing code to work a large number of file paths, Pathname’s utility functions are much easier, and more reliable, than manually parsing strings yourself. However, when I ran my build the first time I was greeted with: TypeError: no implicit conversion of Pathname into String.
I don’t recall exactly what it was, but I was doing something like passing a Pathname to File#link or something, which barfed when given anything other than exactly-a-String. Pathname#to_s does exist, and renders the file path as a string like you’d expect; however, there is no Pathname#to_str: you can’t use Pathname in places that explicitly expect a String!
This blog’s a personal project, so I was able to solve this with a little
With the creation of this implicit conversion method, I could then use
Pathname anywhere that expects a String and have it converted automatically.
Ruby has other handy implicit-conversion methods, for things like arrays and hashes. You can read about them more in the rdocs: Implicit Conversions.