Check if file contains string

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

    I would use:

    if File.readlines("testfile.txt").grep(/monitor/).any?
    

    or

    if File.readlines("testfile.txt").any?{ |l| l['monitor'] }
    

    Using readlines has scalability issues though as it reads the entire file into an array. Instead, using foreach will accomplish the same thing without the scalability problem:

    if File.foreach("testfile.txt").grep(/monitor/).any?
    

    or

    if File.foreach("testfile.txt").any?{ |l| l['monitor'] }
    

    See "Why is "slurping" a file not a good practice?" for more information about the scalability issues.

提交回复
热议问题