Global variables usage

I declared two files.One to hold the value of a global variable.And the
other to print it.

1)to hold variables (var.rb)

Code:

$foo = 500
  1. to print the global variable (gprint.rb)

Code:
loop do
puts $foo
end

But when I print it ,I get the value “nil” being printed not 500.What
could be the problem?

I did read some tutorials online but dint help.Could some please tell
why I am not able to access the global variable between two .rb files in
the same folder?

Please let me know.

On Fri, Feb 19, 2010 at 3:02 PM, di vi [email protected] wrote:

  1. to print the global variable (gprint.rb)

Code:
loop do
puts $foo
end

where in this code (gprint.rb) does it say that you are accessing the
file var.rb ?
read on require and load…

best regards -botp

botp wrote:

On Fri, Feb 19, 2010 at 3:02 PM, di vi [email protected] wrote:

  1. to print the global variable (gprint.rb)

Code:
� �loop do
� �puts $foo
� �end

where in this code (gprint.rb) does it say that you are accessing the
file var.rb ?
read on require and load…

best regards -botp

Load and require execute the complete program…I want only the value of
global variables to change in the respective .rb file.

2010/2/19 di vi [email protected]:

where in this code (gprint.rb) does it say that you are accessing the
file var.rb ?
read on require and load…

best regards -botp

Load and require execute the complete program…I want only the value of
global variables to change in the respective .rb file.

Well, there’s an obvious solution to that: place the global variable
in a file on its own which you load from all places that need it.
However, I am not sure that this is generally a good idea. What do
you need that for?

Kind regards

robert

On Fri, Feb 19, 2010 at 09:00:47PM +0900, Robert K. wrote:

in a file on its own which you load from all places that need it.
However, I am not sure that this is generally a good idea. What do
you need that for?

. . . or edit the file you’re loading/requiring so that it will only
conditionally execute code in the file if the file is executed directly,
and not if it is called as a library using load or require. For
instance:

> cat included_file.rb
#!/usr/bin/env ruby
$foo = 'foo'
$bar = 'bar'
if $0 == __FILE__
  # code to be executed if file
  # called directly for execution
end

> cat including_file.rb
#!/usr/bin/env ruby
load 'included_file.rb'
if $0 = __FILE__
  # do stuff with $foo
  # do stuff with $bar
end

Apologies if I’m off-base – I haven’t read the whole thread in detail,
because I just rejoined the list after a hiatus.