簡體   English   中英

如何在 Ruby 中獲取調用方法的名稱?

[英]How to get calling method's name in Ruby?

我想創建一個父 class (或模塊),其方法對調用父方法的子類的方法名稱執行某些操作。 例子:

class Foo
  def foo
    puts __method__
  end
end

class Bar < Foo
  def bar
    foo
  end
end

Bar.new.bar被調用時,它會打印:foo ,但我想讓它打印bar Foo#foo方法應該如何滿足這種行為?

嘗試caller

class Foo
  def foo
    puts caller[0][/`.*'/][1..-2]
  end
end

class Bar < Foo
  def bar
    foo
  end
end

Bar.new.bar #=> bar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM