Search code examples
rubyfilefwritefread

Ruby - Can't write to file after checking if empty


The program should write "File Empty" if the file is empty; otherwise, it should write "File Full". Here's what I have so far:

fname = "fileTest.txt"
somefile = File.open(fname, "w")

if File.readlines(somefile).grep(/monitor/).size == 0
    somefile.write("File Empty")
else
    somefile.write("File Full.")
end

somefile.close

When I run this the first time, fileText.txt is empty, so the program writes "File Empty". When I run it a second time, the program should write "File Full", but the file still reads "File Empty".

The if statement should be checking if the file is empty, but I don't it is working correctly. What am I doing wrong?

EDIT - Problem Solved:

fname = "fileTest.txt"
somefile = File.open(fname, "a")

if File.zero?(somefile)
  somefile.write("File Empty")
else
  somefile.write("File Full.")
end

somefile.close

Solution

  • Your code doesn't really match your question.

    You say:

    The program should write "File Empty" if the file is empty; otherwise, it should write "File Full"

    But you code says this:

    if File.readlines(somefile).grep(/monitor/).size == 0
        somefile.write("File Empty")
    else
        somefile.write("File Full.")
    end
    

    You are grepping for an RE that matches monitor and, if you don't find it, you're code says to write "File Empty".

    "File Empty" does not contain "monitor", so when the program is run a second time, it once again reports "file empty"

    If you are actually trying to solve the problem I quoted, then you can use File.zero?("filename") as a quick and easy solution.