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 3: Keeping Our Balance

Adrian Manteza
Adrian Manteza
2,527 Points

Part 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

I 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.

Yes - 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
Adrian Manteza
2,527 Points

So the new .to_s method that was rewritten inside the BankAccount class is applicable only when you use puts bank_account?