Gaston Flores
Gaston Flores

Reputation: 2467

Check if each string from array is contained by another string array

Sorry I'am new on Ruby (just a Java programmer), I have two string arrays:

I need to check each patter over each "file path". I do with this way:

@flag = false
["aa/bb/cc/file1.txt","aa/bb/cc/file2.txt","aa/bb/dd/file3.txt"].each do |source|
  ["bb/cc/","zz/xx/ee"].each do |to_check|
    if source.include?(to_check)
      @flag = true
    end
  end 
end
puts @flag

This code is ok, prints "true" because "bb/cc" is in source.

I have seen several posts but can not find a better way. I'm sure there should be functions that allow me to do this in fewer lines. Is this is possible?

Upvotes: 0

Views: 103

Answers (2)

Sagar Pandya
Sagar Pandya

Reputation: 9497

As mentioned by @dodecaphonic use Enumerable#any?. Something like this:

paths.any? { |s| patterns.any? { |p| s[p] } }

where paths and patterns are arrays as defined by the OP.

Upvotes: 4

tadman
tadman

Reputation: 211560

While that will work, that's going to have geometric scaling problems, that is it has to do N*M tests for a list of N files versus M patterns. You can optimize this a little:

files = ["aa/bb/cc/file1.txt","aa/bb/cc/file2.txt","aa/bb/dd/file3.txt"]

# Create a pattern that matches all desired substrings
pattern = Regexp.union(["bb/cc/","zz/xx/ee"])

# Test until one of them hits, returns true if any matches, false otherwise
files.any? do |file|
  file.match(pattern)
end

You can wrap that up in a method if you want. Keep in mind that if the pattern list doesn't change you might want to create that once and keep it around instead of constantly re-generating it.

Upvotes: 1

Related Questions