T
Tim Morgan
Forgive this very basic question, but Googling has not answered my
question, and I'm sure it's a simple one for the gurus here.
I've been using Ruby for years, and I've always had questions about
how it handles scope. Usually Ruby just does what I would expect it
to.
In reading about lexical vs. dynamic scope on various places on the
Web, I read that Ruby has lexical (static) scope. But I cannot prove
it to myself with code. For example, the following produces one (1) --
not zero (0) as I would expect it to if Ruby was truly statically
scoped:
x = 0
f = Proc.new { x }
g = Proc.new {
x = 1
f.call
}
puts g.call
# => 1
(I purposely used Procs instead of regular methods here since Ruby
methods cannot see the top-level "x" variable at all, which is a whole
other issue.)
Is Ruby really dynamically scoped?
question, and I'm sure it's a simple one for the gurus here.
I've been using Ruby for years, and I've always had questions about
how it handles scope. Usually Ruby just does what I would expect it
to.
In reading about lexical vs. dynamic scope on various places on the
Web, I read that Ruby has lexical (static) scope. But I cannot prove
it to myself with code. For example, the following produces one (1) --
not zero (0) as I would expect it to if Ruby was truly statically
scoped:
x = 0
f = Proc.new { x }
g = Proc.new {
x = 1
f.call
}
puts g.call
# => 1
(I purposely used Procs instead of regular methods here since Ruby
methods cannot see the top-level "x" variable at all, which is a whole
other issue.)
Is Ruby really dynamically scoped?