Any way to determine which object called a method?

Joseph Weissman picture Joseph Weissman · Apr 24, 2010 · Viewed 14.2k times · Source

I'm hoping that Ruby's message-passing infrastructure means there might be some clever trick for this.

How do I determine the calling object -- which object called the method I'm currently in?

Answer

Peter picture Peter · Apr 24, 2010

You can easily look at the line of code that called the function of interest through

caller.first

which will tell you the filename and line number which called the relevant function. You could then back-calculate which object it was.

However, it sounds like you're more after some object that called a certain function, perhaps within an instance method. I'm not aware of a method for figuring this out - but I wouldn't use it anyway, since it seems to violate encapsulation badly.