Coirotomas Coirotomas - 7 months ago 7
Ruby Question

How to give precedence to a method over a local variable

I have a method and a local variable with the same name

x
:

class A
def x; 5 end
end

x = 10


I want to refer to the method
x
without using
self.x
. For example, I want:

A.new.instance_eval{x} # => 10


to return
5
. Is that possible?

Answer

Yes, in several ways:

A.new.instance_eval{x()} # => 5
A.new.instance_eval{send(:x)} # => 5

If you only allow x, it is impossible. Local variables have lexical scope, and has precedence over method in case of ambiguity.

Comments