1

I'm looping over some files, and need to skip files that have a certain substring in their path. These substrings are defined as an array. For example:

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

  puts file
end

The code above successfully skips any file path with __macosx, but I need to adapt it to work with an array of substrings, something like the following:

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

How can I do that, while avoiding having to write an extra loop to iterate over the substring array?

1 Answer 1

2

You can use use Enumerable#any? to check like this:

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this really helped. Although I think I needed to convert ignore_file to a regular expression to use =~? The line that works in the end is: next if Init::IGNORE_PATHS.any? { |ignore_path| /#{ignore_path}/ =~ file.name.downcase }
@JohnDorean - yes, good catch. I updated my answer to use the regex syntax w/ the i for case insensitive.
You could also use a combined regular expression, e.g. Regexp.union(Init::IGNORE_PATHS)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.