Why do this Ruby object have both to_s and inspect methods that appear to do the same thing?

prosseek picture prosseek · Apr 12, 2010 · Viewed 37.6k times · Source

Why do this Ruby object both a to_s and inspect methods that appear to do the same thing?

The p method calls inspect and puts/print calls to_s for representing the 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 : 0
Graph : 0
  • Then, why does Ruby have two functions do the same thing? What is the difference between to_s and inspect?
  • And what's the difference between puts, print, and p?

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

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

Answer

David picture David · Apr 12, 2010

inspect is used more for debugging and to_s for end-user or display purposes.

For example, [1,2,3].to_s and [1,2,3].inspect produce different output.