2

Suppose I write a Ruby script with not class definition. I can still create class variables and class level instance variables:

@@var = "class variable!";
@var = "class instance variable!";

puts @@var;
puts @var;

These variables belong to a top-level context object.

Is this top-level context object similar to the global context in JavaScript in that it can serve as a kind of top-level namespace? For example, is there a way to do something like this in Ruby using the "top-level context object"?

var arrStore1 = new Ext.data.ArrayStore({/*...*/});
/* same call again, using the global context object */
var global = window;
var arrStore2 = new global.Ext.data.ArrayStore({/*...*/});
Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
  • You can but probably shouldn't. The main context isn't supposed to be polluted this way with instance variables. – tadman Jan 10 '13 at 20:08
  • @tadman - I'm asking more if it behaves as a root namespace, which would allow access other classes using that variable; `self.Dir.pwd` or something. – Richard JP Le Guen Jan 10 '13 at 20:15
  • `self.Dir` shouldn't work. `Dir` is a root namespace entry, just like any other class. Generally instance variables are used in classes and instances of classes *only*. It's highly irregular to see them used for other purposes. JavaScript has different idea of context and scoping than Ruby. Also, `@var` would be private to the root namespace, not accessible to others as a JavaScript variable would be since instance variables are always private to their owner. – tadman Jan 10 '13 at 22:18

2 Answers2

2

The top level object is like any other ruby object. You can include modules into it, it can have instance variables. But it's not really a global context.

For more detail, see the SO: What is "main" in Ruby?

Community
  • 1
  • 1
wless1
  • 3,489
  • 1
  • 16
  • 12
1

It's almost always best to create a top-level namespace entry of some kind and put your global or quasi-global variables in there:

module GlobalOptions
  def self.option
    @option
  end

  def self.option=(value)
    @option = value
  end
end

GlobalOptions.option = :foo
GlobalOptions.option
# => :foo

Inside of Rails you have mattr_accessor which can generate these for you automatically.

tadman
  • 208,517
  • 23
  • 234
  • 262