Skip to content

Instantly share code, notes, and snippets.

@dnagir
Created January 18, 2012 02:34
Show Gist options
  • Save dnagir/1630480 to your computer and use it in GitHub Desktop.
Save dnagir/1630480 to your computer and use it in GitHub Desktop.
When Ruby undefined becomes defined
> irb
1.9.3p0 :001 > a
NameError: undefined local variable or method `a' for main:Object
from (irb):1
from /Users/dnagir/.rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'
1.9.3p0 :002 > b
NameError: undefined local variable or method `b' for main:Object
from (irb):2
from /Users/dnagir/.rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'
1.9.3p0 :003 > a = b
NameError: undefined local variable or method `b' for main:Object
from (irb):3
from /Users/dnagir/.rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'
1.9.3p0 :004 > a = a
=> nil
1.9.3p0 :005 > a
=> nil
@alg
Copy link

alg commented Jan 18, 2012

Here's the funny thing I wanted to fix in Ruby last year:

a = 1 if defined?(a)
=> 1

The thing is that if the engine sees you assign something to an unknown name, it assumes it's a variable and places it in the var table. When it later checks for whether it's defined, it sees the name in the var table and the condition becomes true. Ideally, they should have either skipped analyzing the code inside the conditional block, or placed var names in temporary table that is merged with the main one if the condition is true.

@dnagir
Copy link
Author

dnagir commented Jan 18, 2012

Another good one.
I think I did come around that too.

Ruby makes me scratch my head pretty often :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment