为什么这个Ruby对象同时具有to_s和inspect方法,而这些方法似乎都执行相同的操作?

时间:2022-06-01 21:00:49

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

为什么这个Ruby对象既是to_s对象,又是检查那些似乎做同样事情的方法?

The p method calls inspect and puts/print calls to_s for representing the object.

p方法调用inspect和put /print调用to_s来表示对象。

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?
  • 那么,为什么Ruby有两个函数做同样的事情呢?to_s和inspect有什么区别?
  • And what's the difference between puts, print, and p?
  • 那么,put, print和p的区别是什么呢?

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

如果我注释to_s或inspect函数,我将得到以下结果。

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

9 个解决方案

#1


43  

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

inspect更多用于调试,to_s用于终端用户或显示目的。

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

例如,[1,2,3]。to_s和[1,2,3]。检查生成不同的输出。

#2


30  

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.

inspect是一个方法,默认情况下,它告诉您类名、实例的object_id,并列出实例变量。

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和put将对象的to_s方法的值放到STDOUT中。如Ruby文档所示,对象#to_s返回一个表示对象的字符串——用于最终用户可读性。

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

除了put自动附加换行之外,print和put是完全相同的,而print则不是。

#3


13  

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.

与Python相比,to_s就像__str__,检查就像__repr__。to_s给出一个字符串,而inspect给出对象的字符串表示形式。如果愿意,可以使用后者来构造对象。

#4


5  

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

此外,在某些对象上有一个to_str方法,当您需要一个类似字符串的对象时,您可以调用它,而不仅仅是一个字符串表示。(试着在IRB:[1,2,3]。to_str失败,但[1,2,3]。to_s不会)。我觉得我应该提一下,因为我以前被它咬过。

#5


3  

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

put通常打印对对象应用to_s的结果,而p打印检查对象的结果。

There is a subtle difference between inspect and to_s:

检查和to_s之间有一个细微的区别:

  • inspect, when applied on an object, returns the object hex code along with the instance variable
  • 当应用到对象上时,inspect将返回对象十六进制代码以及实例变量
  • to_s, when applied on an object,returns only the object hex code

    当对对象应用to_s时,只返回对象十六进制代码

    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

#6


3  

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

对于刚开始使用Ruby Koans的人来说,to_s和inspect的输出不同的一个简单示例是:

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

#7


1  

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

从Rails教程

#8


1  

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."

“inspect方法与to_s非常相似,只是它返回的字符串试图向您显示构建您传递给它的对象的ruby代码。”

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

因此,inspect方法将返回一个数组,例如……

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

Where as puts / to_s will return

Where as put / to_s将返回?

25
16
9
4
1
0

#9


0  

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

请参考下面的链接以获得更多的信息和示例,以解释“to_s”和“inspect”之间的差异,以及“put”和“p”之间的差异。https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/108-displaying-objects

#1


43  

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

inspect更多用于调试,to_s用于终端用户或显示目的。

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

例如,[1,2,3]。to_s和[1,2,3]。检查生成不同的输出。

#2


30  

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.

inspect是一个方法,默认情况下,它告诉您类名、实例的object_id,并列出实例变量。

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和put将对象的to_s方法的值放到STDOUT中。如Ruby文档所示,对象#to_s返回一个表示对象的字符串——用于最终用户可读性。

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

除了put自动附加换行之外,print和put是完全相同的,而print则不是。

#3


13  

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.

与Python相比,to_s就像__str__,检查就像__repr__。to_s给出一个字符串,而inspect给出对象的字符串表示形式。如果愿意,可以使用后者来构造对象。

#4


5  

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

此外,在某些对象上有一个to_str方法,当您需要一个类似字符串的对象时,您可以调用它,而不仅仅是一个字符串表示。(试着在IRB:[1,2,3]。to_str失败,但[1,2,3]。to_s不会)。我觉得我应该提一下,因为我以前被它咬过。

#5


3  

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

put通常打印对对象应用to_s的结果,而p打印检查对象的结果。

There is a subtle difference between inspect and to_s:

检查和to_s之间有一个细微的区别:

  • inspect, when applied on an object, returns the object hex code along with the instance variable
  • 当应用到对象上时,inspect将返回对象十六进制代码以及实例变量
  • to_s, when applied on an object,returns only the object hex code

    当对对象应用to_s时,只返回对象十六进制代码

    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

#6


3  

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

对于刚开始使用Ruby Koans的人来说,to_s和inspect的输出不同的一个简单示例是:

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

#7


1  

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

从Rails教程

#8


1  

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."

“inspect方法与to_s非常相似,只是它返回的字符串试图向您显示构建您传递给它的对象的ruby代码。”

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

因此,inspect方法将返回一个数组,例如……

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

Where as puts / to_s will return

Where as put / to_s将返回?

25
16
9
4
1
0

#9


0  

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

请参考下面的链接以获得更多的信息和示例,以解释“to_s”和“inspect”之间的差异,以及“put”和“p”之间的差异。https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/108-displaying-objects