メソッドの中から自身のメソッド名を知る方法

Ruby 1.8 の時は、こんな感じだった。

RUBY_VERSION                    # => "1.8.7"

class Object
  def current_method
    caller.first.scan(/`(.*)'/).to_s
  end
end

def foo
  current_method                # => "foo"
end

def bar
  foo
  current_method                # => "bar"
end

bar
current_method                  # => ""

Ruby 1.9 になって、Kernel.caller と Array.to_s の仕様が変わったみたい。

RUBY_VERSION                    # => "1.9.1"

class Object
  def current_method
    caller.first.scan(/`(.*)'/).to_s
  end
end

def foo
  current_method                # => "[[\"foo\"]]"
end

def bar
  foo
  current_method                # => "[[\"bar\"]]"
end

bar
current_method                  # => "[[\"<main>\"]]"

どうするのがいいのかなぁ?

caller.first.scan(/`(.*)'/).first.first  # 1.8 だと動かない

caller.first.scan(/`(.*)'/).join         # BK 気味

トップレベルからは、そんなに頻繁に呼ばれないだろうと考えると、こんな感じかなぁ。

RUBY_VERSION                    # => "1.9.1"

class Object
  def current_method
    begin
      caller.first.scan(/`(.*)'/).first.first
    rescue
      ""
    end
  end
end

def foo
  current_method                # => "foo"
end

def bar
  foo
  current_method                # => "bar"
end

bar
current_method                  # => "<main>"