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 Ruby Objects and Classes Variables and Methods The to_s method

lindseyk
lindseyk
4,506 Points

I'm not totally clear on the reason one should create a to_s method?

In what causes would one want to print the name of an instance as a string, rather than just having a name attribute? Maybe I'm not fully understanding the function?

1 Answer

In the video he creates a variable called name that is assigned to an instance of the Name class: Name.new.

He then calls puts on it: puts name. This prints the name object as a String; it's a funny looking object that isn't very useful.

puts uses the in-built Ruby method: to_s. In this case, the result of using it is not producing anything desirable, so Jason chooses to override the to_s method, by defining it in his Name class.

Then, when puts name is executed, Ruby uses the custom to_s method that has just been defined, rather than the native in-built one. This produces a result that is more desirable to Jason.

lindseyk
lindseyk
4,506 Points

Ah, I understand now that he is overriding the existing to_s. That makes sense. Thanks!! Is there a reason that is preferable to doing something like this?

Class Dog

attr_reader :name

def initialize(name) @name = name

some more methods and such down here...

end end

fido = Dog.new("Fido")

puts fido.name

or maybe

puts "Hey, there's #{fido.name}!"

(Sorry for the very strange formatting of this response! I'm writing from an iPad and can't figure out how to insert a code sample... Also, my published comment isn't keeping new lines, tabs, etc in the way I'm writing them. )