检索数组中包含的子字符串的索引

Retrieving index of substrings contained within array

我正在遍历某些文件,需要跳过路径中包含特定子字符串的文件。这些子字符串被定义为一个数组。例如:

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

我该怎么做,同时避免必须编写额外的循环来遍历子字符串数组?

您可以使用 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