Why is to_s not returning an object ID and not what I told it to?

to_s is one of the most useful methods in Ruby. Almost every class you ever write should have an implementation of it; it’s useful when debugging, it’s useful when outputting information for people.

But sometimes you call puts @my_object and it ignores your to_s method and just returns the object ID; something like #<C:0x0055ff9f85ba48>

Why? How do you make it work right?

Well the trick is that to_s means “to string” – your implementation has to return a string object, otherwise Ruby will ignore it and do its own thing (showing you the object ID).

So always make sure you return a string object and all will be well.

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe