I have noticed the following code is syntactically correct:
class Foo
bar = 3
end
Now, I know that instance variables are accessed by @
, and class variables by @@
, but I couldn't figure out where bar
is stored in this case or how to access it.
How can I find bar
's scope?
The body of a class in Ruby is just executable Ruby code. These are indeed local variables (no quotation needed) and follow the "regular" rules being local variables. You can access them in the body of the class. If you literally want the scope where bar
is defined, you can use Kernel.binding
:
class Foo
bar = 42
@@scope = binding
def self.scope
@@scope
end
end
Foo.scope.local_variables # => [:bar]
Foo.scope.local_variable_get(:bar) # => 42
A thing to note - using def
changes the scope, therefore, they won't be visible inside methods defined using def
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With