2015-11-03 116 views
1

我正在循环某些文件,并且需要跳过其路径中具有特定子字符串的文件。这些子字符串被定义为一个数组。例如:检索数组中包含的子字符串的索引

Dir.glob("#{temp_dir}/**/*").each do |file| 
    # Skip files in the ignore list 
    if (file.downcase.index("__macosx")) 
    next 
    end 

    puts file 
end 

上面的代码成功地将跳过__macosx任何文件路径,但我需要去适应它的子字符串数组,像下面的东西的工作:

if (file.downcase.index(["__macosx", ".ds_store"])) 
    next 
end 

我怎样才能这样做,而避免必须编写一个额外的循环迭代子字符串数组?

回答

2

您可以根据Enumerable#any?检查这样的:

ignore_files = %w(__macosx ds_store) 
Dir.glob("#{temp_dir}/**/*").each do |file| 
    # Skip files in the ignore list 
    next if ignore_files.any? { |ignore_file| %r/ignore_file/i =~ file } 

    puts file 
end 
+0

谢谢,这真是帮了。虽然我认为我需要将'ignore_file'转换为正则表达式才能使用'=〜'?最后工作的那行是:'next如果Init :: IGNORE_PATHS.any? {| ignore_path | /#{ignore_path}/=〜file.name.downcase}' –

+0

@JohnDorean - 是的,好的。我更新了我的答案,以便将不区分大小写的正则表达式使用“/ i”。 – Anthony

+2

您也可以使用组合正则表达式,例如'Regexp.union(初始化:: IGNORE_PATHS)' – Stefan