Confusion with local variable assignment in ruby

Hi,

I am having some confusions about local variable assignments…

x + 1 # undefined local variable or method `x’ for main:Object
(NameError)

But why not the same error happened in the below case ?

x = x+1

undefined method `+’ for nil:NilClass (NoMethodError)

Excerpts from Love U Ruby’s message of 2013-11-23 19:44:45 +0100:

undefined method `+’ for nil:NilClass (NoMethodError)

Because in the first case, ruby can’t know whether x is a method called
without parentheses or a local variable. It opts for the first
possibility,
but can’t find such a method and raises an exception.

In the second case, instead, ruby sees
x =
and understand that x can’t be a method (you can’t assign to a method),
so it correctly decides x is a local variable. It then attempts to add 1
to x, which is done by calling the + method on x. Of course, x is nil,
so you get a NoMethorError exception.

I hope this helps

Stefano

Stefano C. wrote in post #1128425:

Excerpts from Love U Ruby’s message of 2013-11-23 19:44:45 +0100:

In the second case, instead, ruby sees
x =
and understand that x can’t be a method (you can’t assign to a method),
so it correctly decides x is a local variable. It then attempts to add 1
to x, which is done by calling the + method on x. Of course, x is nil,
so you get a NoMethorError exception.

I hope this helps

Stefano

Yes, now I am ok… Let me some more confusions that I am having still

class A
attr_accessor :x
def result
x = x + 1
end
end

a = A.new
a.x = 4
a.x # => 4
a.result # result': undefined method+’ for nil:NilClass
(NoMethodError)

I expected a.result would return 5. In the line x = x + 1, why x(in
x + 1) part has been treated as local variable instead of getter method
call ?

Excerpts from Love U Ruby’s message of 2013-11-23 20:45:42 +0100:

I hope this helps
end

a = A.new
a.x = 4
a.x # => 4
a.result # result': undefined method+’ for nil:NilClass
(NoMethodError)

I expected a.result would return 5. In the line x = x + 1, why x has
been treated as local variable instead of getter method call ?

It’s the same issue as before. As soon as ruby sees

x = …

it decides x is a local variable. To avoid this, you have to make the
receiver of the x method explicit, using self:

self.x = x + 1

In this case, there is no ambiguity, as self.x can only be a method.

Stefano