Reputation: 3096
I am doing some metaprogramming in ruby and in the method_missing implementation I wonder If i can tell if the call site is being used in an assignment ?
For example :
x = special_function 'param'
would be caught by the method_missing implementation. I would like to know if I can tell if the function was invoked like this :
special_function 'param'
I.e. without a left hand side on the assignment.
Is it possible in ruby to tell the difference between the above two examples in code ?
Upvotes: 4
Views: 86
Reputation: 83680
Here is no any difference for your case, as I understand.
Ruby will invoke your code from right to left.
So it will try to execute firstly:
special_function 'param'
And then it'll asign the result to x
.
So if special_function
method is not defined will throw it to method missing
and if it will handle it somehow it will return some vaue back. And x
will be assigned to this actual value
PS as I read @ne0lithic_coder answer looks like I've understand your question wrong. You can see this topic: Can Ruby return nothing?
PPS
If you don't want to assign x
in some cases you can try:
val = special_function 'param'
x = val unless val.nil? # if val
Upvotes: 1
Reputation: 3152
I wouldn't think this is possible, simply because every method always returns something and evaluating a method is independent of the context in which it is called.
The assignment is incidental in this case and just happens to make use of what the method returns.
Is there a reason you want to distinguish these calls? Maybe there are other ways to look at the same problem by following a naming convention in your methods to help you separate their uses.
Upvotes: 4