Arrays 检索数组中包含的子字符串的索引
我正在遍历一些文件,需要跳过路径中有特定子字符串的文件。这些子字符串定义为数组。例如:Arrays 检索数组中包含的子字符串的索引,arrays,ruby,substring,Arrays,Ruby,Substring,我正在遍历一些文件,需要跳过路径中有特定子字符串的文件。这些子字符串定义为数组。例如: Dir.glob("#{temp_dir}/**/*").each do |file| # Skip files in the ignore list if (file.downcase.index("__macosx")) next end puts file end 上面的代码成功地跳过了带有\uuu macosx的任何文件路径,但我需要对其进行调整以使用一系列子字符串,如下所
Dir.glob("#{temp_dir}/**/*").each do |file|
# Skip files in the ignore list
if (file.downcase.index("__macosx"))
next
end
puts file
end
上面的代码成功地跳过了带有\uuu macosx
的任何文件路径,但我需要对其进行调整以使用一系列子字符串,如下所示:
if (file.downcase.index(["__macosx", ".ds_store"]))
next
end
如何做到这一点,同时避免编写额外的循环来迭代子字符串数组?您可以使用以下方法进行检查:
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
谢谢,这真的很有帮助。虽然我认为我需要将
ignore_file
转换为正则表达式以使用=~
?最后一行是:next if Init::IGNORE_path.any?{| ignore_path |/#{ignore_path}/=~file.name.downcase}
@JohnDorean-是的,抓住了。我更新了我的答案,使用正则表达式语法w/theI
不区分大小写。您也可以使用组合正则表达式,例如Regexp.union(Init::IGNORE_path)