所以我喜歡使用 rubyinspect?? 進行除錯,但是我有一個類,它有一個包含 6000 多個元素的陣列,并且每當我puts obj.inspect的陣列使整個螢屏變得混亂時。有什么方法可以使陣列屬性從檢查中隱藏?
class Test
def initialize
@x = 1
@array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
end
def myinspect
# ??
end
end
c = Test.new
puts c.inspect # <Test:0x00007f1d49e33b00 @x=1, @array=[1, 2, 3, 4, 5, 6, 7, 8, 9]>
puts c.myinspect # <Test:0x00007f1d49e33b00 @x=1>
uj5u.com熱心網友回復:
要使用my_inspect我們需要以下正則運算式,我以自由間距模式撰寫了它以使其自記錄。
R = /
,\ @ # match ', @'
\w # match one or more word characters
=\[ # match '=['
.*? # match one or more characters lazily
\] # match ']'
/x # invoke free-spacing regex definition mode
這是按慣例寫的
R = /, @\w =\[.*?\]/
然后,我們創建一個類Test以包含一個保存整數的實體變數和兩個保存陣列的實體變數,以及方法initialize和my_inspect.
class Test
def initialize
@x = 1
@array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
@tom_cat = ['Fluffy', 'Tiger', 'Max']
end
def my_inspect
inspect.gsub(R,'')
end
end
當inspect在一個實體上呼叫時,Test我們不希望參考保存陣列的實體變數。
Test.new.inspect
#=> "#<Test:0x00007f962c102740 @x=1>"
瞧!
另一種方法是覆寫內置的inspect. 有兩種方法可以做到這一點。首先是為內置方法創建別名inspect,正如@MasaSakano 在他/她的回答中所做的那樣。另一種方法是預先添加一個包含新方法的模塊inspect。我將在下面描述該選項。
第一步是使用新方法創建一個模塊inspect將附加到類Test中。
module M
def inspect
method(__method__).super_method
.call
.gsub(R,'')
end
end
請參閱內核#__method__和Method#super_method。
接下來創建Test前置模塊的類M的類。
class Test
def initialize
@x = 1
@array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
@tom_cat = ['Fluffy', 'Tiger', 'Max']
end
prepend M
end
看Module#prepend。
試試看!
Test.new.inspect
#=> "#<Test:0x00007f962c852900 @x=1>"
瞧!
uj5u.com熱心網友回復:
您可以在 Ruby 中重新定義任何方法。因此,就您而言,您可以inspect在課堂上重新定義Test重新定義。
這是一個例子。
class Test
alias_method :inspect_original, :inspect if ! self.method_defined?(:inspect_original) # backup
def inspect
content = instance_variables.map{|i|
sprintf("%s=%s", i, instance_variable_get(i).inspect) if i != :@array
}.compact.join(" ")
"<#{self.class.name}:0x#{object_id.to_s(16).rjust(16, '0')} #{content}>"
end
end
Test.new.inspect
# => "<Test:0x00000000001fb490 @x=1>"
uj5u.com熱心網友回復:
可能可以對物件 id 使用更多的優雅轉換,但不確定
class Test
def initialize
@x = 1
@array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
end
def myinspect
"#<#{self.class.name}:0x#{(object_id * 2).to_s(16).rjust(16, '0')} @x=#{instance_variable_get(:@x)}>"
end
end
接著
test = Test.new
puts test.inspect
#<Test:0x000055e35c5dc4c0 @x=1, @array=[1, 2, 3, 4, 5, 6, 7, 8, 9]>
puts test.myinspect
#<Test:0x000055e35c5dc4c0 @x=1>
如果沒有這種轉換,您的代碼將不會那么難看
例如導軌不使用這個物件 id
可能你也不需要它
uj5u.com熱心網友回復:
所以我決定做一個inspect_except
class Test
def initialize
@x = 1
@array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
end
def inspect_except(*attrs)
r = "<#{self.class.name}:#{object_id}"
instance_variables.each do |var|
next if attrs.include? var
r = " #{var}=#{instance_variable_get var}"
end
r = ">"
end
end
c = Test.new
puts c.inspect_except(:@array)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/532919.html
標籤:红宝石
上一篇:如何優化到1個查詢?
