Rubyで今実行中のメソッド名を知る

http://www.lostway.org/~tko/cgi-bin/bakagaiku.rb?bakaid=200510131
を見て、exception起こしてbacktractで無理矢理取得、って方法を知る。アタマイイ!ということでObjectに組み込んでみた。ひょっとしたら使う機会があるかも?

class Object
  def current_method
    begin
      raise StandardError
    rescue StandardError => e
      e.backtrace[1].scan(/`(.*)'/).to_s
    end
  end
end

で、下記のような挙動に。

def foo
  p current_method
end

foo
#=> 'foo'

追記

id:ha-tan:20051014:1129218253 によると、callerを使えば例外を投げなくともbacktraceの情報を取得できるらしい。こっちの方法のほうが全然シンプル。素晴らしい!

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