What is the __repr__ equivalence in ruby?

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

Is there a Ruby equivalent? I thought it was to_s, but I had an OBJECT OB, it does not seem to call the to_s method.

Added

Something is wrong with me, p OBJECT seems to be calling the to_s method as follows. I have some tips from my answers to my other question. - Question of Ruby's to_s method (from Axx 2nd edition book)

 # 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 
+7
python ruby
source share
2 answers
  obj.inspect => string 

Returns a string containing the human-readable representation of obj . If not overridden, the to_s method is to_s 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 . By default, to_s prints the class of the object and the encoding of the object identifier. As a special case, the top-level object, which is the original context for executing Ruby programs, returns `` main. ''

a source

+9
source share
An object

p uses #inspect.

+3
source share

All Articles