Why ruby object has two to_s and inspect methods that (looks like) do the same thing?

Posted by prosseek on Stack Overflow See other posts from Stack Overflow or by prosseek
Published on 2010-04-12T21:41:06Z Indexed on 2010/04/12 21:53 UTC
Read the original article Hit count: 301

Filed under:
|
|

The p calls inspect, and puts/print calls to_s for representing its object.

If I run

class Graph
  def initialize
    @nodeArray = Array.new
    @wireArray = Array.new
  end
  def to_s # called with print / puts
    "Graph : #{@nodeArray.size}"
  end
  def inspect # called with p
    "G"
  end
end

if __FILE__ == $0
  gr = Graph.new
  p gr
  print gr
  puts gr
end

I get

G
Graph : 0Graph : 0
  • Then, why does ruby has two functions do the same thing? What makes the difference between to_s and inspect?
  • And what's the difference between puts/print/p?

If I comment out the to_s or inspect function, I get as follows.

#<Graph:0x100124b88>#<Graph:0x100124b88>

© Stack Overflow or respective owner

Related posts about ruby

Related posts about print