首页 > ruby > 给ruby程序以及ruby待操作的文件以完整的路径

给ruby程序以及ruby待操作的文件以完整的路径

2009年12月30日 leleba 发表评论 阅读评论

有的时候需要给ruby程序以及ruby待操作的文件以完整的路径,举例说明吧:

在g:\ding\anpc\163_anpc.rb程序中有如下代码:

3.times {
load ‘..\anpc\data_163.rb’
load ‘..\bin\bin_163.rb’
}

如果在g:\ding\anpc\ 下执行163_anpc.rb, 程序可以正常运行,但如果在别的路径,比如c:\,执行g:\ding\anpc\163_anpc.rb,程序就会报错,说找不到data_163.rb和bin_163.rb。

解决问题的方法是给ruby程序以完整的路径,如下所示:

3.times {
load File.join(File.dirname(__FILE__), ‘data_163.rb’)
load File.join(File.dirname(__FILE__), ‘../bin/bin_163.rb’)
}

类似的例子:

在g:\ding\anpc\data_163.rb程序中有如下代码:

#初始化user
users = []
File.open(‘user_163_anpc.txt’) do |f|
f.each_line do |line|
words = line.split(‘ ‘)
users << {:user => words[0], :password => words[1]}
end
end

该程序在g:\ding\anpc\ 下执行data_163.rb, 文件操作正常,但如果在别的路径,比如c:\,执行g:\ding\anpc\data_163.rb,程序就会报错,说找不到文件user_163_anpc.txt。

解决问题的方法是给待操作的文件以完整的路径,如下所示:

#初始化user
users = []
users_filename = File.join(File.dirname(__FILE__), ‘user_sina_anpc.txt’)
File.open(users_filename) do |f|
f.each_line do |line|
words = line.split(‘ ‘)
users << {:user => words[0], :password => words[1]}
end
end

本文原创于http://www.sdgz.cn



分类: ruby 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.
      
                  
      

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word