0

I see the following behavior in both MRI 2.0 and jruby 1.7.16.1:

irb(main):001:0> a 
NameError: undefined local variable or method `a' for main:Object
        from (irb):1
        from /usr/bin/irb:12:in `<main>'
irb(main):002:0> a = 2 unless true
=> nil
irb(main):003:0> a
=> nil
irb(main):004:0>

I expected a to remain undefined because = has higher precedence than unless. What am I missing?

Ajit George
  • 3,239
  • 1
  • 19
  • 10

2 Answers2

0

a = 2 unless true is evaluated like this:

unless true
  a = 2
end

precedence doesn't come into play because its a different scope.

eabraham
  • 4,094
  • 1
  • 23
  • 29
0
a  #=>NameError: undefined local variable or method `a' for main:Object

The parser can not decide if this is a local variable OR METHOD, as the error says.

a = 2 unless true

Here the parser is able to recognize this is meant to be a variable, and it is defined (not initialized). It will be initialized if the statement is executed. Uninitialized variables evaluate to nil.

steenslag
  • 79,051
  • 16
  • 138
  • 171