Forum: Ruby Method name

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Michael (Guest)
on 2006-05-17 16:05
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
Mark V. (Guest)
on 2006-05-17 16:36
(Received via mailing list)
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.
Dave B. (Guest)
on 2006-05-17 19:37
(Received via mailing list)
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
Uncutstone W. (Guest)
on 2006-05-17 21:41
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.
Mike N. (Guest)
on 2006-05-17 22:42
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 ''
Uncutstone W. (Guest)
on 2006-05-17 23:00
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.
This topic is locked and can not be replied to.