2
class A
  def initialize(string, number)
    @string = string
    @number = number
  end

  def to_s
    "In to_s:\n   #{@string}, #{@number}\n"
  end
  def to_a
    "In to_a:\n   #{@string}, #{@number}\n"
  end
end
puts a = A.new("hello world", 5)

output is

 In to_s:
   hello world, 5

How is the to_s method called automatically?

Why isn't another method called automatically such as to_a?

Since I did not write puts in the to_s method, why is output printed.

1
  • Note that printing the new object, not creating it, is what triggers the call to to_s. Nov 3, 2013 at 8:58

3 Answers 3

7

You're sending it to puts, which will try to render the object as a string using to_s.

If you changed your last line to: puts A.new("hello world", 5).to_a, it would instead call to_s on the returned Array and A's to_s would not be called.

1

puts generally prints the result of applying to_s on an object read more here

0

In addition to @numbers1311407 answer

whenever you try any code in irb

it calls to_s implicitly.

and as @numbers1311407 answer explains.

puts call to_s implicitly

1
  • 4
    Close - it calls inspect implicitly, which then calls to_s. Aug 20, 2012 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.