2012-04-26 40 views
0

所以我有以下的小腳本來組織我們得到的報告的文件設置。使用Ruby來自動化大型目錄系統

#This script is to create a file structure for our survey data 

require 'fileutils' 

f = File.open('CustomerList.txt') or die "Unable to open file..." 
a = f.readlines 
x = 0 

while a[x] != nil 

    Customer = a[x] 
    FileUtils.mkdir_p(Customer + "/foo/bar/orders") 
    FileUtils.mkdir_p(Customer + "/foo/bar/employees") 
    FileUtils.mkdir_p(Customer + "/foo/bar/comments") 
    x += 1 

end 

一切似乎while前工作,但我不斷收到:

'mkdir': Invalid argument - Cust001_JohnJacobSmith(JJS) (Errno::EINVAL) 

這將是從CustomerList.txt第一線。我需要對數組入口做些什麼纔算是字符串嗎?我是不匹配變量類型還是什麼?

在此先感謝。

+0

爲什麼Customer是一個常量? – inger 2012-04-26 19:25:13

+0

是「Cust001_JohnJacobSmith(JJS)」的第一行嗎? – inger 2012-04-26 19:26:29

+0

是的,這將是文件的第一行。 – JHStarner 2012-04-26 19:27:39

回答

1

以下爲我工作:

IO.foreach('CustomerList.txt') do |customer| 
    customer.chomp! 
    ["orders", "employees", "comments"].each do |dir| 
    FileUtils.mkdir_p("#{customer}/foo/bar/#{dir}") 
    end 
end 

數據,像這樣:

$ cat CustomerList.txt 
Cust001_JohnJacobSmith(JJS) 
Cust003_JohnJacobSmith(JJS) 
Cust002_JohnJacobSmith(JJS) 

有幾件事情,使它更像是紅寶石的方法:打開時

使用的塊文件或迭代數組,這樣您就不必擔心關閉文件或直接訪問數組。

正如@inger所指出的,本地增值業務以小寫字母,客戶開頭。

當你想要一個字符串變量的值爲usign#{}比用+連接更具有魯棒性。

另請注意,我們使用chomp起飛尾隨換行符! (它改變了var,在方法名稱後面註明)

+0

工作很好。非常感謝。看起來我需要儘快做一些Ruby閱讀。 – JHStarner 2012-04-26 20:52:27