Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Build an Address Book in Ruby Class Design Phone Number Class

Nick Stoneman
Nick Stoneman
10,093 Points

Is anyone able to expand on how the 'to_s' method in the Phone_Number class is accessible to the Contact class?

I'm not clear on how the final method we create at the end of this video is a able to access the to_s method made in the other file. Further, why has the method been called 'to_s'? I'm guessing 'to_s' is actually the ruby 'to string' method. But isn't using an existing ruby method to name OUR method bad form? A bit confused here.

3 Answers

It is my understanding that the require "./filename" line is necessary to reference a class contained in another file. You are correct, the to_s method is short for "to string" and it overrides any existing implementation of to_s.

Daniel Crews
Daniel Crews
14,008 Points

The to_s method of the Phone_Number class is accessible because the phone_number variable is an object of the Phone_Number class. It was instantiated in the line

phone_number = Phone_Number.new

It is idiomatic in Ruby to define a to_s method in class definitions and not considered bad form. It is used so that calling to to_s on the object is more informative than the standard implementation. Keep in mind, you're not overriding the String class's to_s method here. You're defining a new one for the class that you've created.

I was confused about this too but just found a great explanation and example(s) over on rubymonk.com. I'll provide the link below, it's really helpful. It talks about puts, p, inspect, and to_s and how they relate. Wish I read it earlier to be honest. Anyway, according to them puts outputs (prints) the result of applying to_s on an object. So in a situation where you decide to override to_s in your class (like in the video), puts will automatically take on that new behavior of to_s. In other words once to_s got overridden, we were essentially creating a new behavior for puts as it relates to the PhoneNumber object.

Another thing I found interesting, apparently the overriding of to_s (within a class) is encouraged to fit the specific needs of your class.

http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/108-displaying-objects