From: Phrogz Date: 2007-09-22T12:05:07+09:00 Subject: Re: foo || 0 will cause exception but not for himself On Sep 21, 8:37 pm, SpringFlowers AutumnMoon wrote: > if foo is undefined, it will throw exception when referred to... as in > try 1, 2, and 3 below. However, it won't throw exception when assigned > to himself... how is that interpreted? > > irb(main):001:0> foo > NameError: undefined local variable or method `foo' for main:Object > from (irb):1:in `Kernel#binding' > > irb(main):002:0> foo || 0 > NameError: undefined local variable or method `foo' for main:Object > from (irb):2:in `Kernel#binding' > > irb(main):003:0> bar = foo || 0 > NameError: undefined local variable or method `foo' for main:Object > from (irb):3:in `Kernel#binding' > > irb(main):004:0> foo = foo || 0 > => 0 > > irb(main):005:0> foo > => 0 When Ruby says "undefined local variable or method", what it means is "Hey, I don't know what this is, and I don't know if it's supposed to be a variable or a method." When you write "foo = ..." Ruby says, "Ah ha! Foo is supposed to be a variable. I'll treat it as one." That's my (somewhat informed) guess anyhow. The determination of the method/variableness of 'foo' is determined before runtime, when the lexer/parser is analyzing the program. This is similar to why this code... if foo=42 p foo end works just fine, but this code: p foo if foo=42 throws an error. When it first see's foo in the first code sample, it knows that it is a variable. When it first sees foo in the second code sample, it doesn't know what it is yet, and throws an error to indicate its confusion.