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 Address Class: Part 1

Andrew Walters
Andrew Walters
8,876 Points

to_s formatting

Hey guys. In the "Build an address book" course in the Ruby track, we override the to_s method and pass along the format principle def to_s(format = "short") end for example. What does the format do? What kinds of options do we have with it? Thanks!

Emily Coltman
Emily Coltman
Courses Plus Student 9,623 Points

Could I also please ask what's behind using "to_s" as a method when it already exists by default? Why not simply give the new method another name? To me it feels confusing to redefine / override "to_s". What's the rationale behind that, please?

2 Answers

Short is the default argument value for the method. Format is just a variable and could be anything. You could put options = "short", or frmt = "short" and it would work the same so long as your case statement inside the method mirrors that variable name (case format, case options, case frmt) Having a default argument like this allows you to call the method without providing any arguments. IE: puts address_book.to_s and still get something in return.

This is how I understand it at this point anyway. :)

Andrew Walters
Andrew Walters
8,876 Points

Thanks to the both of you, this made the most sense to me :)

"short" is a default value for format if you don't specify a value for it. Calling to_s() the value of format would be "short". Calling to_s("long") the value of format will be "long"

Andrew Walters
Andrew Walters
8,876 Points

But what does format itself mean?

rowend rowend
rowend rowend
2,926 Points

Andrew Walters it can mean anything depending of your context. This is a simple method with a simple argument given by the programmer. In this case this says: hey displays the information in short or long format.