tags:

views:

84

answers:

2

Right now my code works as such:

def method_a
  self.method_b ==> 'method_b'
end

def method_b
  puts self.name_of_calling_method
end

def name_of_calling_method
  if  /`(.*)'/.match(caller.first)
    return $1
  else
    return nil
  end
end

Instead of method_b printing 'method_b', how can I print the name of the calling method - 'method_a'?

A: 

Replace caller.first with caller[1].

sepp2k
+3  A: 

When you are in name_of_calling_method called from method_b then method_a is 1 entry higher up the call stack so you want caller[1] in name_of_calling_method rather than caller.first or caller[0].

Because you've put the regexp on the left hand side and the the index into caller on the right you won't need an additional nil check for the case where method_b is called directly and caller[1] is nil - your no match else case will cover it.

mikej