2
如何以編程方式獲取定義當前正在執行的代碼的類?我需要找到上課的時候控制流過由於super()
多種方法定義運行:Ruby:獲取定義當前正在執行的代碼的類
class A
def foo
puts(get_current_class)
end
end
class B < A
def foo
puts(get_current_class)
super
end
end
class C < B
def foo
puts(get_current_class)
super
end
end
C.new.foo
# => C
# => B
# => A
我知道怎麼弄的方法名稱(使用__callee__
,caller_locations
或__method__
);但是班級呢?
但是,我甚至不能遠程想象的任何情況,其中一個實際上需要這個。我的意思是,如果你在'B'類中寫了一個'foo'方法,那麼你知道你在'B'類。它就在屏幕的頂部。 –
是的,我同意......我幾乎可以肯定地只是寫代碼中的'puts「從類B」'調用foo(),而不是像上面那樣「編程」。不過,如果您想快速將調試語句放置在多個地方,也許這會很有用。 –