Get the name of the currently executing method

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


Even better than my first answer you can use __method__:

class Foo
  def test_method
    __method__
  end
end

This returns a symbol – for example, :test_method . To return the method name as a string, call __method__.to_s instead.

Note: This requires 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/25762.html

上一篇: 检查一个变量是否被定义?

下一篇: 获取当前正在执行的方法的名称