亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲得調用方法的名稱?

如何獲得調用方法的名稱?

UYOU 2019-10-24 14:23:14
Ruby中有沒有一種方法可以在方法內部找到調用方法的名稱?例如:class Test  def self.foo    Fooz.bar  endendclass Fooz  def self.bar    # get Test.foo or foo  endend
查看完整描述

3 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

puts caller[0]

也許...


puts caller[0][/`.*'/][1..-2]


查看完整回答
反對 回復 2019-10-24
?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

在Ruby 2.0.0中,您可以使用:


caller_locations(1,1)[0].label

它比Ruby 1.8+解決方案快得多:


caller[0][/`([^']*)'/, 1]

backports當我有時間(或請求請求?。r將包含在其中。


查看完整回答
反對 回復 2019-10-24
?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

相反,您可以將其編寫為庫函數,并在需要時進行調用。代碼如下:


module CallChain

  def self.caller_method(depth=1)

    parse_caller(caller(depth+1).first).last

  end


  private


  # Copied from ActionMailer

  def self.parse_caller(at)

    if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at

      file   = Regexp.last_match[1]

      line   = Regexp.last_match[2].to_i

      method = Regexp.last_match[3]

      [file, line, method]

    end

  end

end

要觸發上述模塊方法,您需要這樣調用: caller = CallChain.caller_method


查看完整回答
反對 回復 2019-10-24
  • 3 回答
  • 0 關注
  • 663 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號