Check if file contains string

后端 未结 4 568
无人及你
无人及你 2021-01-31 15:40

So I found this question on here, but I\'m having an issue with the output and how to handle it with an if statement. This is what I have, but it\'s always saying that it\'s tru

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 15:54

    Grep will give you an array of all found 'monitor's. But you don't want an array, you want a boolean: is there any 'monitor' string in this file? This one reads as little of the file as needed:

    if File.open('test.txt').lines.any?{|line| line.include?('monitor')}
      p 'do something'
    end
    

    readlines reads the whole file, lines returns an enumerator which does it line by line.

提交回复
热议问题