【问题标题】:Retrieving index of substrings contained within array检索数组中包含的子字符串的索引
【发布时间】:2016-02-03 13:12:21
【问题描述】:

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

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

我怎样才能做到这一点,同时避免编写额外的循环来迭代子字符串数组?

【问题讨论】:

    标签: arrays ruby substring


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这真的很有帮助。虽然我认为我需要将ignore_file 转换为正则表达式才能使用=~?最后起作用的行是:next if Init::IGNORE_PATHS.any? { |ignore_path| /#{ignore_path}/ =~ file.name.downcase }
    • @JohnDorean - 是的,很好。我更新了我的答案以使用带有i 的正则表达式语法来区分大小写。
    • 您也可以使用组合正则表达式,例如Regexp.union(Init::IGNORE_PATHS)
    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2022-09-22
    相关资源
    最近更新 更多