Mark Hubbart
6/27/2005 1:02:00 AM
On 6/26/05, Devin Mullins <twifkak@comcast.net> wrote:
> Ryan Leavengood wrote:
>
> > Because the variable doc is local to the top-level scope and can't be
> > seen inside the methods of Crap.
>
> That is interesting, though. In most cases, variables defined in the
> outer scope are available in the inner scope. This applies in the case
> of begin...end, blocks, and the if/while/etc control flow operators. It
> seems that the same rule does not apply to method and class definitions.
> Why? Is there anything else to which it doesn't apply?
Unlike some other languages, variables that are not in scope in Ruby
are completely inaccessible (unless you resort to certain tricks).
Class, Module and Method definitions introduce new scopes, so outside
variables will be entirely invisible. Conditionals and looping
statements (ie, if..else, while..end, case..when..end) do not
introduce new scopes, so they can access variables that are outside
them, and variables defined inside them will be accessible outside the
statement.
Blocks are a little more complicated; they don't really introduce a
new scope, but any variables defined only inside a block will not
escape the block.
foo = 23
class Bar # new scope! foo is not accessible
baz = 42
def qux # another new scope! no baz for you!
puts baz # yoiks, that'll be a NameError
end
end
And for blocks:
name = "Mark"
5.times{puts name} # works
5.times{|n| n+=1}
puts n # doesn't work, n stays in the block
n = nil # n exists before the block
5.times{|n| n+=1}
puts n # outputs: "6"
Hope this helps, and isn't too confusing :) Except for blocks, it's
actually a simpler scheme than most other languages; no masking of
variable names in outer scopes.
cheers,
Mark