从此ruby字符串中提取文件路径

时间:2013-07-27 14:57:49

标签: ruby arrays string filenames

我使用ruby Dir方法获取目录中的所有文件名。像这样:

 dir_files = Dir["/Users/AM/Desktop/07/week1/dailies/regionals/*.csv"]

这给了我一个数组,其中列出了每个元素:

 /Users/AM/Desktop/07/week1/dailies/regionals/ch002.csv
 /Users/AM/Desktop/07/week1/dailies/regionals/ch014.csv
 /Users/AM/Desktop/07/week1/dailies/regionals/ch90.csv
 /Users/AM/Desktop/07/week1/dailies/regionals/ch112.csv
 /Users/AM/Desktop/07/week1/dailies/regionals/ch234.csv

我试图只提取上述字符串中匹配的部分:“regionals / * .csv”

我如何在Ruby中做到这一点?

以下无效

@files_array.each do |f|
     f = f.split("/").match(/*.csv/)
    i = f.include?(".csv")
    puts "#{i.inspect}"

    #self.process_file(f[i])
 end

这是一个聪明的方法吗?我打算将每个文件名的返回字符串传递给辅助方法进行处理。但正如您所看到的,所有csv文件都位于与执行脚本不同的目录中。 执行此操作的脚本位于

 /Users/AM/Desktop/07/week1/dailies/myScript.rb

由于

2 个答案:

答案 0 :(得分:3)

无论文件模式如何,这都将始终回发最终目录和文件名:

@files_array.map { |f| f.split("/")[-2..-1].join("/") }
#=> ["regionals/ch002.csv", "regionals/ch014.csv", "regionals/ch90.csv", "regionals/ch112.csv", "regionals/ch234.csv"]

答案 1 :(得分:1)

这为您提供了所需的值:)

dir_files.map {|path| path[/regionals\/.*.csv/]}
#=> ["regionals/ch002.csv", "regionals/ch014.csv", "regionals/ch90.csv", "regionals/ch112.csv", "regionals/ch234.csv"]