Frank G. wrote:
For example, I have a variable that shows up in three different files
and looks like:
maxColumns = 30
I’d like to know what the most elegant way is to define it in one place
and share it, across files.
The best way to define a constant is using a constant 
MAX_COLUMNS = 30
Put this in a source file (e.g. limits.rb) then require ‘limits’ where
you need it.
For any code which might be re-used or shared, you’d be better keeping
your constants in their own namespace:
module MyStuff
MAX_COLUMNS = 30
end
This can be referenced as MyStuff::MAX_COLUMNS, but usually your code
would also be inside the same module, so it can just use MAX_COLUMNS.
If your code consists mainly of one class, then just put the constants
inside that class (remember that a Class is also a Module)
class Foo
MAX_COLUMNS = 30
end
…
require ‘foo/constants’
class Foo
def initialize(n)
raise ArgumentError, “Too many columns” if n > MAX_COLUMNS
@cols = n
end
end
If this value is not actually a constant, but might change at runtime
(e.g. from a command-line option), then you could use a
$global_variable, but I’d suggest a class instance variable.
class Foo
@max_columns = 30 # default value
def self.max_columns
@max_columns
end
def self.max_columns=(n)
@max_columns = n
end
end
…
Foo.max_columns = Integer(ARGV[0]) if ARGV[0]
puts Foo.max_columns
Note that class Foo is itself an object (of class Class), and so
@max_columns is an instance variable of the class itself.