Check if array element appears on line

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.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章