Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variables for a class in ruby [duplicate]

Tags:

ruby

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?

like image 637
Gilad Naaman Avatar asked Jan 22 '16 13:01

Gilad Naaman


1 Answers

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.

like image 182
ndnenkov Avatar answered Sep 20 '22 12:09

ndnenkov