Method name

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

···

--
Posted via http://www.ruby-forum.com/.

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.

···

On 5/17/06, Michael <Michael_ee@yahoo.com> 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?

--
R. Mark Volkmann
Object Computing, Inc.

Mark Volkmann wrote:

···

On 5/17/06, Michael <Michael_ee@yahoo.com> 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.

Does this work?

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

Cheers,
Dave

Dave Burt wrote:

Mark Volkmann 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.

···

--
Posted via http://www.ruby-forum.com/\.

uncutstone wu wrote:

Dave Burt wrote:

Mark Volkmann 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 ''

···

--
Posted via http://www.ruby-forum.com/\.

Mike Nelson 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.

···

--
Posted via http://www.ruby-forum.com/\.