Load file to rails console with access to variables defined in this file

Vladimir Tsukanov picture Vladimir Tsukanov · Oct 22, 2011 · Viewed 12.2k times · Source

I work with rails console and often i need to preload some ruby code to work with.

#file that i want to load in rails console
#my_file.rb
a = 1
b = 2
puts a + b 

When i run my console with ./script/console

rails-console :001 > load 'my_file.rb' 
3
 => []
rails-console :002 > a
NameError: undefined local variable or method 'a' for #<Object:123445>

How can i get access to my 'a' and 'b' variables in console?

Answer

Moiz Raja picture Moiz Raja · Oct 22, 2011

When you load a file local variables go out of scope after the file is loaded that is why a and b will be unavailable in the console that loads it.

Since you are treating a and b as constants how about just capitalizing them like so

A = 1
B = 2
puts A+B

Now in you console you should be able to do the following

load 'myfile.rb'
A #=> 1

Alternately you could make the variables in myfile.rb global ($a, $b)