Using "require" in irb, where did my variables go!?

----- "Tim Apple" <timmyrunsfast@gmail.com> wrote:

Hello,

I have a somewhat basic question: lets say that in my working directory
I have a file called my_vars.rb.

It contains:
x = 5.0
puts "your variable x is #{x}"

Now, I fire up irb in my command window, and type in
require "my_vars.rb"

Which outputs, as expected,
your variable x is 5.0
=> true

Now, I want to access that variable again, so I enter in:
puts x

and I get an error saying that x is undefined. It's like it was
temporarily there in memory, but then once it was used, it got thrown
away! Does anyone know how to load in a file and keep using the
variables that were in said file?

Thanks!

The basic construct that you are discovering here is variable scope. It is not that irb lost your variable or ever had it defined in memory. In fact this problem has nothing to do with irb as the following demonstrates:

wes:~> cat > a.rb << EOF

x = 'Hi'
puts x
EOF

wes:~> cat > b.rb << EOF

require 'a'

puts "in b #{x}"
EOF

wes:~> ruby a.rb
Hi
wes:~> ruby b.rb
Hi
b.rb:3: undefined local variable or method `x' for main:Object (NameError)

The variable is only available locally in the original script a.rb. Tthe second script has no knowledge of this variable and it raises the NameError exception. If you want the variable to be available to both script define a global:

wes:~> cat a.rb
$x = 'Hi'
puts $x
wes:~> cat b.rb
require 'a'
puts "in b #{$x}"
wes:~> ruby b.rb
Hi
in b Hi

I wouldn't recommend using global variables in your code but I write this to illustrate the point. You should read more about variable scope here: Programming Ruby: The Pragmatic Programmer's Guide