Ruby - 相当于Python __str __()方法?

Rea*_*nly 5 ruby

在Ruby中,是否有相当于__str__()您可以在Python类上定义的方法?

小智 6

FWIW,检查可能更喜欢__repr__()__str__()

来自图书馆参考...

repr(个体经营)

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the ``official'' string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an ``informal'' string representation of instances of that class is required.


Kyl*_*ton 5

在核心类上,它通常是“检查”。

例如:

irb(main):001:0> puts "array is: #{[1,2,3].inspect}"
array is: [1, 2, 3]
=> nil
irb(main):002:0> puts "array is: #{[1,2,3]}"
array is: 123
=> nil
irb(main):003:0>
Run Code Online (Sandbox Code Playgroud)