检查文件是否包含字符串 [英] Check if file contains string
问题描述
所以我在这里找到了这个问题,但我遇到了输出问题以及如何用if语句处理它。这就是我所拥有的,但它总是说即使文件中不存在文字监视器也是如此
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
应该是==nil吗?我对ruby很新,不知道输出会是什么。
Should it be something like == "nil"? I'm quite new to ruby and not sure of what the outputs would be.
推荐答案
Enumerable#grep 不返回布尔值;它返回一个数组(如何在不传递块的情况下访问匹配项?)。
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
语句中检查数组的大小,即:
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.
这篇关于检查文件是否包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!