Monday, February 21, 2011

Get the name of the currently executing method in Ruby

So $0 is the env variable for the top level Ruby program ... but is there one for the current method?

From stackoverflow
  • From 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
    
  • Even better than my first answer you can use __method__:

    class Foo
      def test_method
        __method__
      end
    end
    

    This includes a : before the name which you can easily remove.

    Note: This requires Ruby 1.8.7.

    Kent Fredric : in `foo': undefined local variable or method `__method__' for main:Object (NameError)
    Mark A. Nicolosi : Sorry, this requires Ruby 1.9... I'll update my post.
    Mark A. Nicolosi : Make that 1.8.7: http://www.ruby-doc.org/core-1.8.7/classes/Kernel.src/M001072.html
    Kent Fredric : just my luck, still on 1.8.6 :)

0 comments:

Post a Comment