正在尝试获取 ruby 中当前 运行 函数的名称

Trying to get the name of the currently running function in ruby

我有一个函数,我想调用它 return 调用它的函数的名称。这是函数:

def get_pos
  func = __method__.to_s
  puts "You are in #{func}"
end

我知道 __method__ return 是当前正在执行的方法的名称。

我正在尝试从 test 调用 get_pos(),这是我想要获得的输出:

def test
  get_pos
end

You are in test

相反,我得到以下内容

You are in get_pos

我明白为什么会这样。由于 __method__ 位于 getpos 函数内部,因此它 return 是该函数的名称。

我知道如果我进行以下更改并将 __method__ 作为参数传递给函数,我将得到预期的结果。即:

def get_pos(method)
  puts "You are in #{method}"
end

def test
  get_pos(__method__.to_s)
end

You are in test

代码已被简化,但它是记录器功能的一部分,我希望能够将代码中有关当前位置的数据转储到日志中,并确切知道模块、class、函数我在。

有没有比每次都将 __method__ 作为参数传递给函数的 better/cleaner 方法来做到这一点?

为什么不使用内核对象中的 __callee__

我重构了你的代码:

def current
  puts __callee__
end

def test_caller
  current
end

test_caller

在这种情况下输出 current

Kernel Object中有各种有趣的方法。我建议看看 API here.

您可以使用 caller_locations which returns an array of Thread::Backtrace::Location 个实例:(默认从索引 1 开始,不包括当前方法)

def foo
  caller_locations.map(&:base_label)
end

def bar
  foo
end

def baz
  bar
end

baz
#=> ["bar", "baz", "<main>"]

所以 foo 是从 bar 调用的,它是从 baz 调用的,它是在 <main> 中调用的。