Pickles
Pickles

Reputation: 11

Ruby Reading and Writing Files

I've the following piece of code. For the code to work correctly it should be reading the lines and writing them to the console. I'm currently only getting Error: first line of file is not a number.

Any help possible would be great.

def write(aFile, number)

  aFile.puts(number)
  index = 0
  while (index <= number)
   aFile.puts(index)
   index += 1
  end
end


def read(aFile)


  count = aFile.gets
  if (is_numeric?(count))
    count = count.to_i
  else
    count = 0
    puts "Error: first line of file is not a number"
  end

  index = 0
  while (count < index)
    line = aFile.gets
    puts "Line read: " + line
    index += 1
  end
end


def main
  aFile = File.new("mydata.txt", "w") 
  if aFile  
    write(aFile, 10)
    aFile.close
    aFile = File.new("mydata.txt", "r") 
    read(aFile)
    aFile.close
  else
    puts "Unable to open file to write or read!"
  end
end

def is_numeric?(obj)
  if /[^0-9]/.match(obj) == nil
    true
  end
  false
end

main

Upvotes: 0

Views: 161

Answers (1)

ray
ray

Reputation: 5552

Please check following,

count = aFile.gets
if (is_numeric?(count))
  count = count.to_i
else
  count = 0
  puts "Error: first line of file is not a number"
end

When you read file lines, you always read lines in text/string (even numbers inside files). So you are always in else block.

Upvotes: 1

Related Questions