获取当前正在执行的方法的名称

$0是顶级Ruby程序的变量,但是对于当前的方法是否有一个?


甚至比我的第一个答案更好,你可以使用__method__:

class Foo
  def test_method
    __method__
  end
end

这会返回一个符号 - 例如:test_method 。 要将方法名称作为字符串返回,请__method__.to_s调用__method__.to_s

注意:这需要Ruby 1.8.7。


从http://snippets.dzone.com/posts/show/2785:

module Kernel
private
    def this_method_name
      caller[0] =~ /`([^']*)'/ and $1
    end
end

class Foo
  def test_method
    this_method_name
  end
end

puts Foo.new.test_method    # => test_method

对于Ruby 1.9+,我建议使用__callee__

链接地址: http://www.djcxy.com/p/25761.html

上一篇: Get the name of the currently executing method

下一篇: method vs. def