Ruby在创建对象时自动调用to_s方法

sag*_*kar 2 ruby ruby-1.9.3

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)
Run Code Online (Sandbox Code Playgroud)

输出是

 In to_s:
   hello world, 5
Run Code Online (Sandbox Code Playgroud)

to_s方法如何自动调用?

为什么不自动调用另一种方法如to_a

由于我没有在to_s方法中写入put ,为什么输出打印.

num*_*407 7

您将其发送给puts,它将尝试使用的对象呈现为字符串to_s.

如果你改变了你的最后一行:puts A.new("hello world", 5).to_a,它会改为调用to_s的返回数组和A的to_s就不叫.