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 ,为什么输出打印.
您将其发送给puts,它将尝试使用的对象呈现为字符串to_s.
如果你改变了你的最后一行:puts A.new("hello world", 5).to_a,它会改为调用to_s的返回数组和A的to_s就不叫.
| 归档时间: |
|
| 查看次数: |
2827 次 |
| 最近记录: |