Check if file contains string
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.
update
#lines are deprecated, Use #each_line instead
if File.open('test.txt').each_line.any?{|line| line.include?('monitor')}
p 'do something'
end
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.