2010-04-07 73 views
3

現在我的代碼工作,例如:如何返回調用方法的字符串名稱?

def method_a 
    self.method_b ==> 'method_b' 
end 

def method_b 
    puts self.name_of_calling_method 
end 

def name_of_calling_method 
    if /`(.*)'/.match(caller.first) 
    return $1 
    else 
    return nil 
    end 
end 

相反method_b打印「method_b」的,我怎麼能打印調用方法的名字 - 「method_a」?

回答

2

caller.first替換爲caller[1]

3

當你在name_of_calling_methodmethod_b稱爲然後method_a 1次進入更高調用堆棧,所以你要在name_of_calling_method而非caller.firstcaller[0]caller[1]

因爲你已經把正則表達式的左側和索引到caller在右邊你將不再需要額外的nil檢查,其中method_b直接調用,caller[1]nil的情況下 - 你無匹配else案件將覆蓋它。

相關問題