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 trialAdrian Manteza
2,527 PointsPart 3:Keeping Our Balance What is the role/function of this method?
What is the function/role of this method?
def to_s
"Name: #{name}, Balance of account : #{sprintf("%0.2f", balance)}"
end
Jason said that it overwrites the .to_s method.
4 Answers
Alexander Revell
5,782 PointsI can't seem to get to the video to see exactly what he's describing here, but yeah it's effectively re-writing the .to_s method for the given object (I think bank account in this case?) so that you can use .to_s (or 'puts' which just calls .to_s - literally 'put to string') to print out what you specify in this new method definition.
eg.
@bank_account = BankAccount.new('Jason')
if the @bank_account has an attr_reader for name then you can call it with @bank_account.name --> should return 'Jason'
Likewise with the account balance, if you have defined a method to return the balance (as I think Jason has done in the video):
@bank_account.balance --> will return the balance (something like 10.00)
So if you specify that the account prints out its name and dollar/cents balance as part of the to_s method, you don't have to manually type all that out each time yourself. You just specify in the new to_s definition what properties of the @bank_account you want it to print out, and that's what it will print when you call to_s.
# So if @bank_account.name == "Jason"
# and @bank_account.balance == 10.00
def to_s
"Name: #{name}, Balance of account : #{sprintf("%0.2f", balance)}"
end
puts @bank_account # --> will print out "Name: Jason, Balance of account : 10.00"
@bank_account.to_s # --> will also print this out.
That was a bit wordier that I intended, hope it makes more sense what he's doing now.
Alexander Revell
5,782 PointsYes - any instance of the BankAccount class may use it by calling puts, and it will print out the string as specified within the method definition. It only changes the to_s method for this context, not anything else.
Adrian Manteza
2,527 PointsSo the new .to_s method that was rewritten inside the BankAccount class is applicable only when you use puts bank_account?
Adrian Manteza
2,527 PointsThanks Alexander!!!!