Ruby - 如何在自身内部获取方法名称? [重复]

时间:2022-01-01 05:14:58

This question already has an answer here:

这个问题在这里已有答案:

I'm trying to get a method name from itself:

我正在尝试从自身获取方法名称:

def funky_method
  self.inspect
end

It returns "main".

它返回“main”。

How can I return "funky_method" instead?

我怎样才能返回“funky_method”呢?

3 个解决方案

#1


21  

Here is the code:

这是代码:

For versions >= 1.9:

对于版本> = 1.9:

def funky_method

    return __callee__

end

For versions < 1.9:

对于版本<1.9:

def funky_method

    return __method__

end

#2


8  

__callee__ returns the "called name" of the current method whereas __method__ returns the "name at the definition" of the current method.

__callee__返回当前方法的“被叫名称”,而__method__返回当前方法的“定义名称”。

As a consequence, __method__ doesn't return the expected result when used with alias_method.

因此,__method__与alias_method一起使用时不会返回预期结果。

class Foo
  def foo
     puts "__method__: #{__method__.to_s}   __callee__:#{__callee__.to_s} "
  end

  alias_method :baz, :foo
end

Foo.new.foo  # __method__: foo   __callee__:foo
Foo.new.baz  # __method__: foo   __callee__:baz

#3


0  

Very simple:

很简单:


def foo
  puts __method__
end

#1


21  

Here is the code:

这是代码:

For versions >= 1.9:

对于版本> = 1.9:

def funky_method

    return __callee__

end

For versions < 1.9:

对于版本<1.9:

def funky_method

    return __method__

end

#2


8  

__callee__ returns the "called name" of the current method whereas __method__ returns the "name at the definition" of the current method.

__callee__返回当前方法的“被叫名称”,而__method__返回当前方法的“定义名称”。

As a consequence, __method__ doesn't return the expected result when used with alias_method.

因此,__method__与alias_method一起使用时不会返回预期结果。

class Foo
  def foo
     puts "__method__: #{__method__.to_s}   __callee__:#{__callee__.to_s} "
  end

  alias_method :baz, :foo
end

Foo.new.foo  # __method__: foo   __callee__:foo
Foo.new.baz  # __method__: foo   __callee__:baz

#3


0  

Very simple:

很简单:


def foo
  puts __method__
end