读取文件和写入文件

时间:2019-05-30 10:41:34

标签: ruby

似乎无法将我的数据读取为整数并打印出数据。加上在def read(afile)函数中count = aFile.gets的关闭流(IOError)。 该程序包括数组,文件和循环。该程序的目的是获取一个数字10,并将该数字写入文件,然后在每一行中从0到10递增。

# takes a number and writes that number to a file then on each line
# increments from zero to the number passed
def write(aFile, number)
  # You might need to fix this next line:
  aFile.puts("number")
  index = 0
  while (index < number)
   aFile.puts(number.to_s)
   index += 1
  end
end

# Read the data from the file and print out each line
def read(aFile)

  # Defensive programming:
  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
  end
end

# Write data to a file then read it in and print it out
def main
  aFile = File.new("mydata.txt", "w") # open for writing
  if aFile  # if nil this test will be false
    write(aFile, 10)
  else
    puts "Unable to open file to write!"
  end

  if aFile
    read(aFile)
  end
  aFile.close
end

# returns true if a string contains only digits
def is_numeric?(obj)
  if /[^0-9]/.match(obj) == nil
    true
  end
  false
end

main

2 个答案:

答案 0 :(得分:0)

这是皮肤代码,可以轻松添加我删除的功能。

def write(a_file, number)
  (1..number).each { |n| a_file.puts(n) }
end

def read(a_file)
  a_file.each  { |line| puts line }
end

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

  a_file = File.open("mydata.txt", "r")
  if a_file
    read(a_file)
  end
  a_file.close
end

main

我发现的主要错误:

旁注:对变量使用Ruby表示法:a_file很好,aFile不好。

答案 1 :(得分:0)

如果要使代码正常工作,请更改:

aFile = File.new("mydata.txt", "w")

收件人:

aFile = File.new("mydata.txt", "r+")

您可以更改:

 count = aFile.gets
 if (is_numeric(count))

收件人:

  count = aFile.gets.to_i
 if (count.is_a?(Fixnum))

,然后摆脱is_numeric?(obj)方法。

您也无需增加计数器,也可以解决该问题。