我在Ruby中试图做的是相当于PHP的include或require语句。Ruby加载/需要文件
在PHP中,当您包含或需要文件时,包含文件中的任何PHP代码都会执行,并且全局范围的变量可以用于包含include的文件。
在Ruby中,我有这样的代码;
# include file snippet
config = {'base_url' => 'http://devtest.com/'}
# main file
Dir.foreach(BASE_ROOT_PATH + 'config') do |file|
if !(file == '.' || file == '..')
filepath = BASE_ROOT_PATH + 'config/' + file
load filepath
end
end
config.inspect
我遇到的问题是,当我运行主文件时,它总是出错与此错误;
/home/skittles/devtest/bootstrap.rb:24:in `<top (required)>': undefined local variable or method `config' for main:Object (NameError)
from <internal:lib/rubygems/custom_require>:29:in `require'
from <internal:lib/rubygems/custom_require>:29:in `require'
from index.rb:27:in `<main>'
我知道,它的拉动在该文件中,因为它没有抛出任何错误。 我试过加载&要求,两者都有相同的错误。我尝试config.inspect并放置配置,仍然是相同的错误。
这几乎就像包含的文件没有执行它里面的代码。这是怎么回事,或者我只是做错了什么?
感谢
我可以问你想要完成什么吗?以错误的顺序加载所有配置文件是导致此错误的原因。您通常只会加载'environment.rb'文件,并且会加载其他所有内容 – PinnyM 2012-02-01 14:58:48
OP没有说他正在使用Rails ... – Chowlett 2012-02-01 15:00:33
http://stackoverflow.com/questions/2699324/ruby-irb - 要求和范围 – Chowlett 2012-02-01 15:04:32