From: ahoward Date: 2003-05-31T00:12:03+09:00 Subject: Re: local variable and local variable in block behave differently On Fri, 30 May 2003, Brian Candler wrote: > On Fri, May 30, 2003 at 09:49:40PM +0900, Seb Clediere wrote: > > I am sligthly surprised by this behaviour: > > > > if false > > b = "" > > From this point, variable "b" is defined (even though the assignment is > never executed, the interpreter has *parsed* an assignment) > > > else > > 1.times { b = "b" } > > end > > This assigns to variable 'b'. Because it already exists outside of the > block, it assigns to this pre-existing variable, instead of bringing a > temporary variable into existence just for the the lifetime of the block. > > > 1.times do > > if false > > a = "" > > else > > 1.times { a = "a" } > > end > > puts defined? a # => local-variable(in-block) > > puts a # => nil > > end > > OK, that's weird... I would have thought that the assignment to 'a' in the > inner block would have bound to the 'a' brought into existence in the outer > block, but it hasn't. my best guess is that: 1.times do #### #### here we are in a block #### if false #### #### assignment is parsed but not executed, 'a' (block-local) is now nil #### a = "" else #### #### at this point, there is no 'a' in *scope*, only a block-local 'a' #### thus the following block creates a new block-local 'a' #### 1.times { a = "a" } end #### #### these statements operate on the only symbol known as 'a' at this #### point, which happen to be the *first* block-local a. this is not the #### same thing as scope, since blocks do not introduce a new scope. #### puts defined? a # => local-variable(in-block) puts a # => nil end this seems to confirm this: a = 42 1.times do if false a = "" else 1.times { a = "a" } end puts defined? a # => local-variable puts a # => a end since here the print statement can operate on an 'a' which is in scope. the first example is sort of bizarre because there never is an 'a' in scope, only block-locals. template = Amrita::TemplateText.new <<-html html -a -- ==================================== | Ara Howard | NOAA Forecast Systems Laboratory | Information and Technology Services | Data Systems Group | R/FST 325 Broadway | Boulder, CO 80305-3328 | Email: ara.t.howard@fsl.noaa.gov | Phone: 303-497-7238 | Fax: 303-497-7259 | ~ > ruby -e 'p % ^) .intern' ====================================