SHARE:
Uncategorized

The “to_s“ and “to_str“ Methods

Flatiron School / 14 January 2013

The following is a guest post by James Vanneman and originally appeared on his blog. James is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

In ruby you can usually get a pretty good idea of what a method does by its name. I got confused when I saw the two methods to_s and to_str which intuitively seem like they both would cast an object to a string. Obviosly ruby wouldn’t have two methods that do the exact same thing so I decided to figure out what the differences were.

The to_s method returns a string representation of the object. Lets look at some examples

So how do these objects respond to to_str?

None of these objects respond to to_str, so what does it do? It turns out that to_str method is a method that ruby calls when it expects an object to be a string and is not. For example when I write "String" + Object.new, ruby will call to_str on Object.new to find it’s string representation. Lets see how we can use this in our code.

The to_str method is implicity called whenever you try to perform a method on a string with an arguement that isn’t a string. You can define this method however you want as in the Person class example, I had the to_str method return the name of the object.

While their method names imply similar behavior, there are big differences between them. Defining to_str in your classes makes it easy to perform operations between strings and your objects.

jQuery DOM ready handlers Previous Post Caching Fragments Next Post