Ruby 窥探:重写 Range 的字符串方法

Ruby in pry: overriding Range's to string methods

我无法以覆盖 to_s / inspect:

的方式窥探显示从 Range 派生的 class 的实例
[1] pry(main)> class RangeInherited < Range
[1] pry(main)*   def initialize(first, last, added=nil)
[1] pry(main)*     super(first, last)
[1] pry(main)*     @added = added
[1] pry(main)*   end  
[1] pry(main)*   def to_s
[1] pry(main)*     "#<".concat(self.class.name, " ", super, " ", @added || "-", ">")
[1] pry(main)*   end  
[1] pry(main)*   alias inspect to_s
[1] pry(main)* end  
=> nil
[2] pry(main)> r = RangeInherited.new(1, 10, "x")
=> 1..10

尽管直接调用 to_s / inspect 会产生想要的结果:

[3] pry(main)> r.to_s
=> "#<RangeInherited 1..10 x>"
[4] pry(main)> r.inspect
=> "#<RangeInherited 1..10 x>"
[5] pry(main)> 

为什么?


在 Marcin Kołodziej 的回答的帮助下,我得出了以下解决方案:

[1] pry(main)> class RangeInherited < Range
[1] pry(main)*   def initialize(first, last, added=nil)    
[1] pry(main)*     super(first, last)        
[1] pry(main)*     @added = added        
[1] pry(main)*   end      
[1] pry(main)*   def to_s    
[1] pry(main)*     "#<".concat(self.class.name, " ", super, " ", @added || "-", ">")        
[1] pry(main)*   end      
[1] pry(main)*   alias inspect to_s    
[1] pry(main)*   def pretty_print(pp)    
[1] pry(main)*     pp.text(to_s)        
[1] pry(main)*   end       
[1] pry(main)* end  
=> :pretty_print
[2] pry(main)> 
[3] pry(main)> r = RangeInherited.new(1, 10, "x")
=> #<RangeInherited 1..10 x>

没有任何 customizationpry 使用 pp(漂亮的打印)作为其输出,而不是 inspect

为了覆盖它,你必须重新定义 pretty_print,像这样:

def pretty_print(pp)
  pp.text(
    "#<".concat(self.class.name, " ", to_s, " ", @added || "-", ">")
  )
end  

你的撬会输出你想要的:

[3] pry(main)> r = RangeInherited.new(1, 10, "x")
=> #<RangeInherited 1..10 x>