self.method?

A

aidy

Hi,

We can write "self.class" to get the current object, but is it possible
to do something like a "self.method" to retrieve the currently running
method?

Cheers

Aidy
 
V

Vincent Fourmond

Hello !
In short, no it is not possible (in an easy way) -- but just wait, and
someone smarter than me will prove me wrong. ;) See also Kernel#caller
[1]

Based on that, you could try something as follows:

def who_am_i?
return caller[0]
end

def meth
p who_am_i?
end

meth

As it returns text, you'll need some regular expression handling, but
that could help you...

Vince, in a ruby mood today...
 
R

Robert Klemme

Based on that, you could try something as follows:

def who_am_i?
return caller[0]
end

def meth
p who_am_i?
end

Thank you, that certainly works

You can also do that without a helper method:

def meth
p caller(0)[0]
end

Note: default argument for caller is 1, which makes it start one level
above.

Kind regards

robert
 
M

MonkeeSage

Vincent said:
Based on that, you could try something as follows:

def who_am_i?
return caller[0]
end

def meth
p who_am_i?
end

meth

As it returns text, you'll need some regular expression handling, but
that could help you...

Vince, in a ruby mood today...

See! I told you that someone smarter than me would come up with a
solution! Never say never unless you want to be proven wrong rather
quickly! ;)

Using Vince's idea:

def who_am_i?
caller[0].match(/`([^']+)'/)[1]
end

def meth
p who_am_i?
end

meth # => "meth"

:)

Regards,
Jordan
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top