variable scope in required files

D

Dave Baldwin

This behaviour has rather surprised me:

file a.rb
a = 10

file b.rb
require "a.rb"
puts a

dave 123% ruby b.rb
b.rb:2: undefined local variable or method `a' for main:Object
(NameError)

dave 124% ruby -v
ruby 1.8.1 (2003-10-31) [powerpc-darwin]

Using $a fixes this but I don't want to do this or I could join the
two files at run time and eval them.

I didn't expect the scope of a to be private to a.rb and can find no
mention in pickaxe about this.

Dave.
 
C

Carlos

This behaviour has rather surprised me:

file a.rb
a = 10

file b.rb
require "a.rb"
puts a

dave 123% ruby b.rb
b.rb:2: undefined local variable or method `a' for main:Object
(NameError)

dave 124% ruby -v
ruby 1.8.1 (2003-10-31) [powerpc-darwin]

Using $a fixes this but I don't want to do this or I could join the
two files at run time and eval them.

I didn't expect the scope of a to be private to a.rb and can find no
mention in pickaxe about this.

If I'm not mistaken, scopes for local variables are created by files,
class/module and method definitions, and blocks.

They don't nest, except for blocks.

For your problem, you can use a constant, or use 'a=nil;
eval(File.read("a.rb")); p a', etc.

--
 
K

Kevin Bullock

This behaviour has rather surprised me:

file a.rb
a = 10

file b.rb
require "a.rb"
puts a

dave 123% ruby b.rb
b.rb:2: undefined local variable or method `a' for main:Object
(NameError)

dave 124% ruby -v
ruby 1.8.1 (2003-10-31) [powerpc-darwin]

Using $a fixes this but I don't want to do this or I could join the
two files at run time and eval them.

I didn't expect the scope of a to be private to a.rb and can find no
mention in pickaxe about this.

In C, unless you declare them extern[1], variables are private to the
file they're declared in. Using the $a notation is equivalent to
declaring the variable extern. It indicates you're using a global
variable instead of a local one.

Perhaps the better question, though, is why do you need a global
variable? Every time I feel the urge to use a global variable, I ask
myself that question.

[1] E.g.: extern a = 1;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,373
Latest member
Desiree036

Latest Threads

Top