14

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 seem 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
Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

17
  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

Pratik Deoghare
  • 35,497
  • 30
  • 100
  • 146
  • @TheMachineCharmer : Could you check my other question - http://stackoverflow.com/questions/2625667/why-ruby-has-to-s-and-inspect ? <> <-- doesn't seem to wrok. – prosseek Apr 12 '10 at 21:42
  • 1
    Inspect - If not overridden, uses the to_s method to generate the string.---Completely true. @prosseek - Try writing a simple class and do to_s and inspect on its instance - both will return the same. inspect has been overridden on predefined classes like Array,Hash ... that's why they print differently. – RubyDubee Apr 13 '10 at 08:14
3

p object uses #inspect.

steenslag
  • 79,051
  • 16
  • 138
  • 171