开发者

What's the __repr__ equivalence in ruby?

The __repr__ function of python is fancy as it is called when print OBJECT is used automatically.

Is there a ruby equivalence for it? I thought it was to_s, but, I had p OBJECT doesn't s开发者_如何学JAVAeem to call the to_s method.

Added

I got something wrong, p OBJECT seems to call to_s method as follows. I got some hints from my the answers to my other question. - Ruby's to_s method question (from Axe book 2nd edition)

# Sample code from Programing Ruby, page 24
class Song
  def to_s
    "Song"
  end
end

class Songson < Song
  def to_s
    super + "<Songson>"
  end
end

song = Songson.new()
p song


  obj.inspect => string

Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.

   [ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
   Time.new.inspect                 #=> "Wed Apr 09 08:54:39 CDT 2003"

 obj.to_s => string

Returns a string representing obj. The default to_s prints the object‘s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns ``main.’‘

source


p object uses #inspect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜