Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...