views:

706

answers:

2

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

+6  A: 

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
Mark A. Nicolosi
+12  A: 

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.

Mark A. Nicolosi
in `foo': undefined local variable or method `__method__' for main:Object (NameError)
Kent Fredric
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
Mark A. Nicolosi
just my luck, still on 1.8.6 :)
Kent Fredric