0

所以我有以下小脚本来进行文件设置,以组织我们得到的报告。

#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. 我需要对数组条目做些什么才能被视为字符串吗?我是不匹配变量类型还是什么?

提前致谢。

4

1 回答 1

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 所指出的,本地变量以小写客户开头。

当您想要字符串中的变量值时,使用 #{} 比与 + 连接更有效。

另请注意,我们使用 chomp! 删除了尾随换行符!(它改变了原地的 var,由方法名称的尾随 ! 注明)

于 2012-04-26T19:44:21.620 回答