How to get the name of the calling method?

2020-01-23 05:20发布

is there a way in Ruby to find the calling method name inside of a method?

For example:

class Test
  def self.foo
    Fooz.bar
  end
end

class Fooz
  def self.bar
    # get Test.foo or foo
  end
end

标签: ruby
7条回答
Emotional °昔
2楼-- · 2020-01-23 06:13

In order to see the caller and callee information in any language, whether it be ruby or java or python, you would always want to look at the stack trace. In some languages, such as Rust and C++, there are options built into the compiler to turn on some sort of profiling mechanism you can view during run time. I do belive one exists for Ruby called ruby-prof.

And as mentioned above, you could look into the execution stack for ruby. This execution stack is an array containing backtrace location objects.

Essentially all you need to know about this command is as follows:

caller(start=1, length=nil) → array or nil

查看更多
登录 后发表回答