Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> 
like image 915
prosseek Avatar asked Apr 12 '10 21:04

prosseek


People also ask

What does inspect method do Ruby?

inspect is a String class method in Ruby which is used to return a printable version of the given string, surrounded by quote marks, with special characters escaped.

What does Ruby provide to allow the creation of object specific methods?

When you call Song. new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new . This gives you a chance to write code that sets up your object's state.

Why everything in Ruby is an object?

Practically everything in Ruby is an Object, with the exception of control structures. Whether or not under the covers a method, code block or operator is or isn't an Object, they are represented as Objects and can be thought of as such.

How Ruby uses the object structure?

In `ruby`, the body of an object is expressed by a struct and always handled via a pointer. A different struct type is used for each class, but the pointer type will always be `VALUE` (figure 1). In practice, when using a `VALUE`, we cast it to the pointer to each object struct.


1 Answers

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.

like image 135
David Avatar answered Oct 21 '22 11:10

David