2013-04-16 50 views
0

我試圖讓從目前的方法被稱爲紅寶石元編程方法的名稱

def first_method 
    my_method 
end 

def second_method 
    my_method 
end 

def my_method 
    puts "called from: #{method_name}" 
end 

和預期產出方法的名稱:

「從名爲:first_method」

「從叫:last_method「

+2

看到這個帖子:http://stackoverflow.com/questions/5100299/how-to-get-the-name -of-的呼法 – mcfinnigan

回答

2
def a 
    c 
end 
def b 
    c 
end 
def c 
    p caller 
end 

a 
#=> ["/Users/phrogz/Desktop/tmp.rb:2:in `a'", "/Users/phrogz/Desktop/tmp.rb:11:in `<main>'"] 
b 
#=> ["/Users/phrogz/Desktop/tmp.rb:5:in `b'", "/Users/phrogz/Desktop/tmp.rb:12:in `<main>'"] 

您可以使用像這樣的正則表達式匹配名稱中的第一個。

This answer有紅寶石2.0+

也看到了更好的解決方案:https://github.com/banister/binding_of_caller