Search code examples
rubymethodsbuilt-in

Trying to get the name of the currently running function in ruby


I have a function that I would like to call and have it return the name of the function it was called from. Here is the function:

def get_pos
  func = __method__.to_s
  puts "You are in #{func}"
end

I understand that __method__ returns the name of the method it is currently being executed in.

I am trying to call get_pos() from test and this is the output I want to get:

def test
  get_pos
end

You are in test

Instead I get the following

You are in get_pos

I understand why this is happening. Since __method__ is located inside the getpos function it returns the name of that function.

I know that if i make the following change and pass __method__ as an argument to the function, I'll get the expected result. Which is:

def get_pos(method)
  puts "You are in #{method}"
end

def test
  get_pos(__method__.to_s)
end

You are in test

The code has been simplified but is part of functionality in a logger where I want to be able to dump data about the current location in the code to a log and know exactly what module,class,function I am in.

Is there a better/cleaner way to do this than passing __method__ as a parameter to the function each time?


Solution

  • Why don't you use __callee__ from Kernel object?

    I refactored your code:

    def current
      puts __callee__
    end
    
    def test_caller
      current
    end
    
    test_caller
    

    Which outputs current in this case.

    There are all sorts of interesting methods in the Kernel Object. I recommend to take a look to the API here.