2009-04-08 50 views
2

在Ruby中,有沒有一種方法可以確定方法的名稱,類似於「類」方法如何返回對象的類型?如何動態確定Ruby中的方法名稱

例如:

def example_method 
    puts method_name 
end 

#=> "example_method" 
+0

2009-04-08 04:57:21

回答

3

試試這個方法,從here

module Kernel 
private 
    def current_method_name 
    caller[0] =~ /`([^']*)'/ and $1 
    end 
end 


class Foo 
def test_method 
    current_method_name # "test_method" 
end 
end 

這個作品在舊版本的紅寶石(< 1.9)。對於更新的版本,請參閱Ben強調的其他StackOverflow答案here