views:

342

answers:

4

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>
+3  A: 

inspect is a method that, by default, tells you the class name, the instance's object_id, and lists off the instance's instance variables.

print and puts are used, as you already know, to put the value of the object's to_s method to STDOUT. As indicated by Ruby's documentation, Object#to_s returns a string representing the object -- used for end-user readability.

print and puts are identical to each other except for puts automatically appends a newline, while print does not.

Mark Rushakoff
+5  A: 

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.

David
+1  A: 

To compare with Python, to_s is like __str__ and inspect is like __repr__. to_s gives you a string, whereas inspect gives you the string representation of the object. You can use the latter to construct an object if you wish.

grokus
+1  A: 

Further, there is a to_str method on certain objects, which you would call when you need a String-like object, and not just a string representation. (Try in IRB: [1,2,3].to_str and it will fail, yet [1,2,3].to_s will not.) I feel I should mention this because I've been bitten by it before :)

RobH