Check if file contains string

后端 未结 4 567
无人及你
无人及你 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:51

    Enumerable#grep does not return a boolean; it returns an array (how would you have access to the matches without passing a block otherwise?).

    If no matches are found it returns an empty array, and [] evaluates to true. You'll need to check the size of the array in the if statement, i.e.:

    if File.readlines("testfile.txt").grep(/monitor/).size > 0
      # do something
    end
    

    The documentation should be your first resource for questions like this.

提交回复
热议问题