Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

ruby - Check if file contains string

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.

question from:https://stackoverflow.com/questions/8408388/check-if-file-contains-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...