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

Here's what I have but it doesn't work.

myArray = ["cat", "dog", "fish"]
File.open('file.txt').each_line { |line|
  puts "Found a line containing array string" if line =~ myArray  #need to fix this logic
}

I've tried include? and any? but don't know if I'm using them right.

UPDATE:: An important part i left out. I need exact matches! so i don't want the statement to return true if it isn't exact. For instance- if my line says "I love my pet doggie" this statement should return false since "dog" is in the array. Not "Doggie"

My mistake on the poor clarification


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.


你可以使用你的数组创建一个正则表达式

myArray = ["cat", "dog", "fish"]
File.open('file.txt').each_line { |line|
  puts "Found a line containing array string" if %r(#{myArray.join('|')}) === line
}

myArray = ["cat", "dog", "fish"]
File.open('file.txt').each_line { |line|
  puts "Found a line containing array string" if myArray.any? { |word| /.*#{word}.*/.match? line}
}

代码未经测试

链接地址: http://www.djcxy.com/p/25688.html

上一篇: 如何获取用户输入并检查数组中的项目?

下一篇: 检查数组元素是否显示在线上