Method name


#1

Hi,

I’m looking around, but I didn’t find a replacement for c++
PRETTY_FUNCTION or FUNC macro.

How can I find out a method’s name at runtime?

Best regards
Michael


#2

On 5/17/06, Michael removed_email_address@domain.invalid wrote:

Hi,

I’m looking around, but I didn’t find a replacement for c++
PRETTY_FUNCTION or FUNC macro.

How can I find out a method’s name at runtime?

I assume you mean the name of the current method. Here’s one way.

name = caller(0).first.split.last

This gives it to you with single quotes around it which you may want
to strip off.


#3

Mark V. wrote:

name = caller(0).first.split.last

This gives it to you with single quotes around it which you may want
to strip off.

Does this work?

def FUNCTION
caller(1).first[/ `(.*)’\Z/, 1]
end

Cheers,
Dave


#4

Dave B. wrote:

Mark V. wrote:

name = caller(0).first.split.last

This gives it to you with single quotes around it which you may want
to strip off.

Does this work?

def FUNCTION
caller(1).first[/ `(.*)’\Z/, 1]
end

Cheers,
Dave

What if I am at the outmost level?
I cannot get a function name , just got something like this:
test.rb:2546

It may not be a perfect solution.


#5

uncutstone wu wrote:

Dave B. wrote:

Mark V. wrote:

name = caller(0).first.split.last

This gives it to you with single quotes around it which you may want
to strip off.

Does this work?

def FUNCTION
caller(1).first[/ `(.*)’\Z/, 1]
end

Cheers,
Dave

What if I am at the outmost level?
I cannot get a function name , just got something like this:
test.rb:2546

It may not be a perfect solution.

It seems to work properly for me on the outermost level.

def FUNCTION
caller(1).first[/ `(.*)’\Z/, 1]
end

def test_method
puts “i’m in ‘#{FUNCTION}’”
end

test_method
puts “outer: i’m in ‘#{FUNCTION}’”

produces,

i’m in ‘test_method’
outer: i’m in ‘’


#6

Mike N. wrote:

i’m in ‘test_method’
outer: i’m in ‘’

I mean at the outmost level, you are still execute in a function’s
context, but you cannot get this function’s name.