Reflection to get method name from within method?

E

Ezra Zygmuntowicz

Friends-

Is there anyway to use reflection or someother technique to get the
name of a method from within the method when it is running?

So if I had this:

def foo
#some magick incantation here that returns the name of the method
"foo"
end


Thanks-
-Ezra
 
S

Sean O'Halpin

Friends-

Is there anyway to use reflection or someother technique to get the
name of a method from within the method when it is running?

So if I had this:

def foo
#some magick incantation here that returns the name of the method
"foo"
end


Thanks-
-Ezra
You could use something like this:

def method_called
caller[0].match(/`([^']+)/).captures[0]
end

def test_me
p method_called
end

test_me
#=> "test_me"

I don't know of any other way (unless perhaps you can get this info
via ParseTree or evil.rb).

Regards,
Sean
 
E

Ezra Zygmuntowicz

Friends-

Is there anyway to use reflection or someother technique
to get the
name of a method from within the method when it is running?

So if I had this:

def foo
#some magick incantation here that returns the name of the method
"foo"
end


Thanks-
-Ezra
You could use something like this:

def method_called
caller[0].match(/`([^']+)/).captures[0]
end

def test_me
p method_called
end

test_me
#=> "test_me"

I don't know of any other way (unless perhaps you can get this info
via ParseTree or evil.rb).

Regards,
Sean

Ok thanks Sean, that will work for what I need to do.

Cheers-
-Ezra
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top