How can I open a file and search for a word inside it using Ruby?
All presented solution have a time complexity of O(n). For simplicity I use String#include?
to check for the word. This could be done instead with a regular expression in the form string=~ regex
.
File.read(filename).include?(word)
If your file is very large, this is not an optimal solution, as you would read the complete file into memory and start searching afterwards. Your memory complexity is O(n)
File.open(filename) do |f|
f.any? do |line|
line.include?(word)
end
end
If your file is very large, but you know your lines are upperbounded by a constant value, you now have a memory complexity of O(1).
File.open(filename) do |f|
tmp= f.read(1024)
next true if tmp.include?(word)
until f.eof?
tmp= tmp[(-1*word.size)..-1] + f.read(1024)
next true if tmp.include?(word)
end
next false
end
In this variant, we are reading equaly sized chunks from the file. So no matter what the conditions of the file are, our memory complexity is O(1)