Ruby in Pry:覆盖Range的字符串方法

时间:2018-10-31 13:38:23

标签: ruby tostring pry

我无法以覆盖to_s / inspect的方式来显示我的类实例,这些实例是从Range派生的:

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

为什么?


借助MarcinKoł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>

1 个答案:

答案 0 :(得分:4)

在没有任何customization的情况下,ifelse使用mutate(漂亮的打印纸)作为输出,而不使用pry

要覆盖它,必须重新定义pp,如下所示:

inspect

您的撬动将输出您想要的内容:

pretty_print