How do I name my objects?

One thing that is often missed when creating a new class is the to_s method.

Ruby uses this all over the place, and in a Rails app, it’s especially useful in making your views more readable.

For example, take a Person class:

It requires that you specify a first name and a last name. So we can then use them to create a combined “name” attribute.

But even better, we define a to_s method that just returns that name.

So when we use our Person in a view, we can show the person’s name as:

Likewise, when we’re in irb or the rails console and we have a reference to a person, we can type

and it will show the person’s name.

It’s a tiny thing that makes a big difference, so I always make sure I define to_s on all my classes.

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