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.
You’re sending it to
puts, which will try to render the object as a string usingto_s.If you changed your last line to:
puts A.new("hello world", 5).to_a, it would instead callto_son the returned Array and A’sto_swould not be called.