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 Build a Bank Account Class Part 4: Printing the register

how can we use to_s when we already redefined it?

How are we able to use to_s on transaction[amount] when we have a to_s method which does something entirely different?

This is called method overriding as you are overriding an existing method with your own implementation. The to_s method does not provide that much functionality by default, so overriding it to be more useful is not that uncommon.

1 Answer

Ari Misha
Ari Misha
19,323 Points

Hiya there! Ruby is really really flexible and versatile behind the scenes, which enables developers to create methods on the fly and also enables to override methods in class implementation. to_s method is defined in the built-in Ruby classes as class method. But you can totally override this method in your custom class implementation and make it bend to output the result of your own. But its not the best practice and is generally avoided coz you wouldnt wanna override built-in methods. Override methods when you really have to.

~ Ari

That didn't answer the question though. He was asking, why Jason was able to use the "to_s" method inside his class, which he already redefined, but it worked as the built-in Ruby method and not like the one he defined himself. An answer would be really helpful, thank you!