开发者

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>


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.


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.


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.


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 :)


For anyone arriving here after starting out with Ruby Koans, a simple example of where to_s and inspect differ in output is this:

nil.to_s     # will yield an empty string, ie ""
nil.inspect  # will yield the string "nil"


puts generally prints the result of applying to_s on an object, while p prints the result of inspecting the object.

There is a subtle difference between inspect and to_s:

  • inspect, when applied on an object, returns the object hex code along with the instance variable
  • to_s, when applied on an object,returns only the object hex code

    class Item
     def initialize(abc)
      @abc=abc
     end
    end
    
    x= Item.new(22)
    
    puts x         #prints object x hex code  
    puts x.inspect #prints object x hex code WITH INSTANCE VARIABLE @abc 
    puts x.to_s    #prints object x hex code
    
    p x            #prints object x hex code WITH INSTANCE VARIABLE @abc
    p x.inspect    #prints object x hex code WITH INSTANCE VARIABLE @abc
    p x.to_s       #prints object x hex code


Answer from Chris Pine's Learn To Program book

"The inspect method is a lot like to_s, except that the string it returns tries to show you the ruby code for building the object you passed it."

Thus the inspect method will return an array for example like this...

[25, 16, 9, 4, 1, 0] 

Where as puts / to_s will return

25
16
9
4
1
0


2.0.0p195 :075 > puts (1..5).to_a                  # Put an array as a string.
1
2
3
4
5
=> nil 
2.0.0p195 :076 > puts (1..5).to_a.inspect          # Put a literal array.
[1, 2, 3, 4, 5]
=> nil 
2.0.0p195 :077 > puts :name, :name.inspect
name
:name
=> nil 
2.0.0p195 :078 > puts "It worked!", "It worked!".inspect    
It worked! 
"It worked!"
=> nil 
2.0.0p195 :079 > p :name                           # Same as 'puts :name.inspect'
:name
=> :name 

From the Rails Tutorial


Refer following link for more information and examples explaining difference between "to_s" and "inspect" as well as difference between "puts" and "p". https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/108-displaying-objects

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜