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 Printing The BankAccount

def to_s doesn't work but does in my programme when I run in my terminal

Hi, I tried the following solution but it throws an error whereas it works fine when I run it from my programme on my terminal.

def to_s puts "Name: #{name}, Balance: #{balance}" end

I tried to convert balance to string as well, nothing works. Plus the puzzle page has to be reloaded everytime these days. Can I suggest the correct answer be given with the solution as sometimes it throws an error even for the right answer. It'll reduce frustration a lot. Thanks. Guru

class BankAccount
  attr_reader :name

  def initialize(name)
    @name = name
    @transactions = []
    add_transaction("Beginning Balance", 0)

  def balance
    balance = 0
    @transactions.each do |transaction|
      balance += transaction[:amount]

  def debit(description, amount)
    add_transaction(description, -amount)

  def credit(description, amount)
    add_transaction(description, amount)

  def add_transaction(description, amount)
    @transactions.push(description: description, amount: amount)


3 Answers

Stone Preston
Stone Preston
42,016 Points

the ruby documentation states:

to_s → string

Returns a string representing obj. The default to_s prints the object’s class and an encoding of the object id.

if you override the to_s method it needs to return the string, not puts it:

def to_s 
    return "Name: #{name}, Balance: #{balance}"

Thank you Stone, it worked, (although it should work with puts also, no)?

Stone Preston
Stone Preston
42,016 Points

while puts might produce the correctly formatted output, the function should really return a string, not puts it. that way you can call to_s and get a string object back, not just see something printed. returning the string makes to_s more usable to other parts of your program, even if most of the time you will be printing the return value

Thanks again for your quick and helpful reply. I'll remember to use return from now on. Appreciate it.