本文介绍了为什么这个 Ruby 对象同时具有 to_s 和 inspect 方法,它们似乎做同样的事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个 Ruby 对象的 to_sinspect 方法看起来都做同样的事情?

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

p 方法调用 inspect 和 puts/print 调用 to_s 来表示对象.

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

如果我跑

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

我明白

G
Graph : 0
Graph : 0

  • 那么,为什么 Ruby 有两个函数做同样的事情呢?to_sinspect 有什么区别?
  • putsprintp 之间有什么区别?
    • 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?
    • 如果我注释掉 to_sinspect 函数,我得到如下.

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

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

      推荐答案

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

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

      例如,[1,2,3].to_s[1,2,3].inspect 产生不同的输出.

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

      这篇关于为什么这个 Ruby 对象同时具有 to_s 和 inspect 方法,它们似乎做同样的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:58