From: Brian Candler Date: 2010-01-27T22:50:15+09:00 Subject: Re: Build an array using data from an exisiting array Sean Warburton wrote: > Why if move ... > > source.each { |doc| dest[doc] = process(doc) } > > above > > def process(input) > "The answer is #{input}" > end > > rather than below like you have, does it throw the error > > undefined local variable or method `source' for # > (NameError) Because you moved it above this line: source = ["foo", "bar", "baz"] which is where 'source' is assigned to. When a ruby script is run, it is first parsed from top to bottom to build as syntax tree, and then it is executed. Because in ruby you never have to declare local variables (no "var foo" here), the system needs to infer what's a local variable, and what's a method call. It does this by looking for assignments. From the point of the assignment statement to the end of the scope, that name is treated as a local variable. puts x # raises an error; no method x() x = 123 puts x # prints 123 if false y = 99 end puts y # prints nil (the assignment to y was seen in # parsing stage, even though it's never executed) -- Posted via http://www.ruby-forum.com/.