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

时间:2022-09-25 18:26:46
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?

to_s方法如何自动调用?

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

为什么不自动调用另一个方法,比如to_a?

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

由于我没有编写to_s方法中的put,所以为什么要打印输出。

3 个解决方案

#1


7  

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

您将它发送到put,它将尝试使用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.

如果你把最后一行改为:put A。新的(“hello world”,5).to_a,它会在返回的数组中调用to_s,而不会调用A的to_s。

#2


0  

In addition to @numbers1311407 answer

除了@numbers1311407答案。

whenever you try any code in irb

无论何时您尝试irb中的任何代码

it calls to_s implicitly.

它调用to_s隐式。

and as @numbers1311407 answer explains.

正如@numbers1311407所解释的那样。

puts call to_s implicitly

将调用to_s隐式

#3


0  

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

put通常打印将to_s应用到此处阅读的对象上的结果

#1


7  

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

您将它发送到put,它将尝试使用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.

如果你把最后一行改为:put A。新的(“hello world”,5).to_a,它会在返回的数组中调用to_s,而不会调用A的to_s。

#2


0  

In addition to @numbers1311407 answer

除了@numbers1311407答案。

whenever you try any code in irb

无论何时您尝试irb中的任何代码

it calls to_s implicitly.

它调用to_s隐式。

and as @numbers1311407 answer explains.

正如@numbers1311407所解释的那样。

puts call to_s implicitly

将调用to_s隐式

#3


0  

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

put通常打印将to_s应用到此处阅读的对象上的结果