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 true even if the word monitor does not exist in the file
if File.readlines("testfile.txt").grep(/monitor/) do something end
Should it be something like == "nil"? I'm quite new to ruby and not sure of what the outputs would be.
Just run the command directly. Add -q option when you don't need the string displayed when it was found. The grep command returns 0 or 1 in the exit code depending on the result of search.
If you have a file opened in nano and need to find a particular string, there's no need to exit the file and use grep on it. Just press Ctrl + W on your keyboard, type the search string, and hit Enter .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With