[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Reflection to get method name from within method?

Ezra Zygmuntowicz

7/10/2006 9:18:00 PM

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

2 Answers

Sean O'Halpin

7/10/2006 9:31:00 PM

0

On 7/10/06, Ezra Zygmuntowicz <ezmobius@gmail.com> wrote:
> 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

Ezra Zygmuntowicz

7/10/2006 9:47:00 PM

0


On Jul 10, 2006, at 2:31 PM, Sean O'Halpin wrote:

> On 7/10/06, Ezra Zygmuntowicz <ezmobius@gmail.com> wrote:
>> 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