From: Jim Weirich Date: 2004-04-24T01:41:52+09:00 Subject: Re: attr_accessor vs. local variable Kirk Haines said: > On Sat, 24 Apr 2004, Jim Weirich wrote: >> Kirk Haines said: >> > This makes sense. When you 'p x', all ruby knows about at that point >> is >> > the accessor method. >> >> Actually, by the time you execute 'p x', Ruby has already compiled the >> method and knows that x is a local variable (since it saw an assignment >> to >> x). > > True. It figures out the local variables at compile time (thus all the > fun with eval and locals), but behaviorally, it seems like since the flow > of execution has not reached the local variable declaration has not been > reached yet, Ruby call the method x() instead. Once the first assignment > takes place, though, the local variable takes precedence over the method. > > It makes sense. Am I misinterpretting what's happening? I stand corrected. References to 'x' that are lexically before the assignment are treated as method calls. References after the the assignment are treated as local variables. But notice it has nothing to do with executeing the assignment. That leads to the following example ... $ cat x.rb def x "METHOD CALL" end def f i = 2 while i > 0 puts x x = "LOCAL VARIABLE" puts x i -= 1 end end f $ $ ruby x.rb METHOD CALL LOCAL VARIABLE METHOD CALL LOCAL VARIABLE -- -- Jim Weirich jim@weirichhouse.org http://onestepback.org ----------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)