I have a file: options.rb
I open IRB and type:
require './options.rb'
#=> true
Try to call a variable in the options
file such as key
(yes this variable is there and the file is saved)
NameError: undefined local variable or method `key' for main:Object
from (irb):2
Why is this not working? By the way also tried to load the file as: irb -r ./options.rb
UPDATE
Also tried to do load './options.rb'
which does return #=> true
but this also does not work.
From the require
docs :
Any constants or globals within the loaded source file will be available in the calling program's global namespace. However, local variables will not be propagated to the loading environment.
So if in options.rb
you have something like:
key = something
(ie key
is a local in the file) then it will not be available in irb. If you make it a global (eg $key = 'something'
) or a constant (eg KEY = 'something'
) it should be available.
If you do not like global variables (as matt suggested) you might also make it an instance variable of the object irb
is running on (an instance of Object
available through self
as ruby always has an object it is operating on) you may also assign
@key='value'
in your file which will give you access to @key
in your irb
-session afterwards. This will work with either require
as with load
, but require
will only load
the file if it has not already done so while load
will always execute the code in the file and thus will end up overwriting the contents of your variable if it has been changed in the mean time.
Ruby is a interpreted language, so for the interpreter to notice your declarations you need to actually 'run' them, the corresponding command in irb is
load './options.rb'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.