Achim Passen wrote:
> I'm trying to figure out how constant lookup works [...]
>
> class A; C=3 end
>
>    $a = A.new
>    $a.instance_eval "C"  # => 3
>    $a.instance_eval {C}
>        # ~> NameError: uninitialized constant C [...]

That's an interesting question!

Michael Linfield already gave an "answer", but I think I have another 
one.

Look here:

class A
  C=3
  def prt_C
    p C
  end
end

a = A.new

def a.another_prt_C
  p C
end

a.prt_C   # OK!
a.another_prt_C   # fails!

the 'another_prt_C' method fails to see the constant. I have the book 
'The Ruby Programming Language' and it has a page about 'Constant 
Lookup'. That page explains that "ruby attempts to resolve a constant 
reference in the *lexical* scope of the reference. This means that it 
first checks the class or module that encloses the constant reference." 
In other words, since our class A doesn't enclose the 'another_prt_C' 
method, this method can't reference the constant (directly). "Lexical" 
means textual. That page also continues to explain that if the lookup 
fails, ruby checks the class hierarchy as well. But the wording of the 
book here is vague and there's roon for interpretation that 
'another_prt_C' indeed shouldn't work and that it's not a bug.

That's why you shouldn't expect instance_eval to see 'C': because this 
constant isn't defined in a class or module *lexically enclosing* your 
block.

You say it's fixed in 1.9. It probably means that 'another_prt_C' too 
works in 1.9, or else my nice theory should be garbage collected! If it 
does work in 1.9, I guess what they fixed is the section I said was 
vague.

-- 
Posted via http://www.ruby-forum.com/.