1

I try to get the name of the method from which current method is called

def first_method
  my_method
end

def second_method
  my_method
end

def my_method
  puts "called from: #{method_name}"
end

and expected output:

"called from: first_method"

"called from: last_method"

Maki
  • 913
  • 4
  • 13
  • 22

1 Answers1

2
def a
  c
end
def b
  c
end
def c
  p caller
end

a
#=> ["/Users/phrogz/Desktop/tmp.rb:2:in `a'", "/Users/phrogz/Desktop/tmp.rb:11:in `<main>'"]
b
#=> ["/Users/phrogz/Desktop/tmp.rb:5:in `b'", "/Users/phrogz/Desktop/tmp.rb:12:in `<main>'"]

You can use a regular expression like caller[0][/`(.+?)'/,1] to match the name in the first one.

This answer has a much better solution for Ruby 2.0+

See also: https://github.com/banister/binding_of_caller

Community
  • 1
  • 1
Phrogz
  • 296,393
  • 112
  • 651
  • 745