Y
Yuh-Ruey Chen
I'm familiar with other popular scripting languages (JS and Python),
and I'm struggling to figure out Ruby's (inanely) complex scoping
mechanisms.
My questions are within the following example:
x = 10
def foo
# how to access x from here?
end
class Klass
# how to access x from here?
def bar
# how to access x from here?
end
end
lambda { x } # I can access x here but why not in foo or Klass or bar?
I sincerely hope I'm missing something here. To me, the inability to
access local variables in an enclosing scope is very counter-
intuitive. I thought Ruby was supposed to be elegant? At the very
least, I expect some sort of "nonlocal" statement similar to Python,
e.g.
def foo
nonlocal x
# I can access x in enclosing scope now
end
And no, I don't want to have to use global variables - that would just
be pollution and would be incredibly unwieldy in large projects.
Frankly, if there was a way to access local variables in enclosing
scopes, there wouldn't even need to be a special global variable
concept.
and I'm struggling to figure out Ruby's (inanely) complex scoping
mechanisms.
My questions are within the following example:
x = 10
def foo
# how to access x from here?
end
class Klass
# how to access x from here?
def bar
# how to access x from here?
end
end
lambda { x } # I can access x here but why not in foo or Klass or bar?
I sincerely hope I'm missing something here. To me, the inability to
access local variables in an enclosing scope is very counter-
intuitive. I thought Ruby was supposed to be elegant? At the very
least, I expect some sort of "nonlocal" statement similar to Python,
e.g.
def foo
nonlocal x
# I can access x in enclosing scope now
end
And no, I don't want to have to use global variables - that would just
be pollution and would be incredibly unwieldy in large projects.
Frankly, if there was a way to access local variables in enclosing
scopes, there wouldn't even need to be a special global variable
concept.