當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby TracePoint.defined_class用法及代碼示例

本文簡要介紹ruby語言中 TracePoint.defined_class 的用法。

用法

defined_class()

返回被調用方法的類或模塊。

class C; def foo; end; end
trace = TracePoint.new(:call) do |tp|
  p tp.defined_class #=> C
end.enable do
  C.new.foo
end

如果方法由模塊定義,則返回該模塊。

module M; def foo; end; end
class C; include M; end;
trace = TracePoint.new(:call) do |tp|
  p tp.defined_class #=> M
end.enable do
  C.new.foo
end

注意: defined_class 返回單例類。

Kernel#set_trace_func 的第 6 個塊參數通過單例類附加的原始類。

這是 Kernel#set_trace_func 和 TracePoint 之間的區別。

class C; def self.foo; end; end
trace = TracePoint.new(:call) do |tp|
  p tp.defined_class #=> #<Class:C>
end.enable do
  C.foo
end

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 TracePoint.defined_class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。