Gaston Flores Gaston Flores - 4 days ago 6
Ruby Question

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:


  • Array with file paths.

  • Array with patterns (can be a path or a file)



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?

Answer

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 OP.

Comments