在HOME/path_test/I中:
负载测试.rb:
require 'yaml'
cnf = YAML::load(File.open('config.yml'))
puts cnf['Hello']
配置.yml:
Hello: world!!!
在HOME/path_test/I中时,我得到了预期的结果:
-bash-3.2$ ruby load_test.rb
world!!!
在家时/(cd..)我明白了
-bash-3.2$ ruby path_test/load_test.rb
path_test/负载测试.rb:3:in `initialize': No such file or directory - config.yml (Errno::ENOENT)
from path_test/负载测试.rb:3:in `open'
from path_test/负载测试.rb:3:in `<main>'
这是正确的行为,但不是我所希望的:)
有没有办法加载文件.yml文件相对于源文件,而不是相对于当前工作目录??
解决方案(load_Test.rb):
require 'yaml'
fn = File.dirname(File.expand_path(__FILE__)) + '/config.yml'
cnf = YAML::load(File.open(fn))
puts cnf['Hello']