1

I would like to check when running a method, if it was called from a different method.

EX:

def method1(foo) if # foo previous method == method2 #code elsif # foo previous method == method 3 #code end end def method2 method1(foo) end 

is there a way to do this?

1

1 Answer 1

4

Yes, you can use caller from Kernel as described in http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-caller, although you'll need to extract the method name from the string that caller[0] returns.

Update: The little regex to extract the method name is shown in https://stackoverflow.com/a/5100339/1008891.

Sign up to request clarification or add additional context in comments.

2 Comments

A small clarification for readers who do not wish to check the docs: caller returns an array of strings that identifies the current execution stack. The first element of the array gives you calling method.
@CarySwoveland Good clarification - my answer was pretty cryptic. I updated it slightly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.