I'm going through a file line by line and I want to check if that line contains any element from an array. for instance if I have:
myArray = ["cat", "dog", "fish"]
and the current line said:
I love my pet dog
The output would say
Found a line containing array string
You have to check each string in the array separately, and use
\b
to match word boundaries to ensure you only get whole words:strings = ["cat", "dog", "fish"].map { |s| Regexp.quote(s) } File.open('file.txt').each_line do |line| strings.each do |string| puts "Found a line containing array string" if line =~ /\b#{string}\b/ end end
Alternatively build a Regex:
strings = ["cat", "dog", "fish"].map { |s| Regexp.quote(s) } pattern = /\b(#{strings.join('|')})\b/ File.open('file.txt').each_line do |line| puts "Found a line containing array string" if line =~ pattern end
Calling
Regexp.quote
prevents characters that have meaning in regular expressions from having an unexpected effect.