1月7日 档案处理。

周六加班,停。周日上午复习SQL语法。


什么是档案?

所有正在执行中的程序和数据,都是放在内存(memory)之中。内存存取速度快,但是容量小而且一关机数据就不见了。
档案则是存在硬盘上,容量大但存取慢,但是关机重来还是继续保存着。

所谓的读取档案就是将数据从硬盘放进内存里面,让程序可以操作。反之写入档案则是将内存的数据写入硬盘进行保存。


如何开档读取和写入

使用 Ruby 的 File API

和IO  https://ruby-doc.org/core-2.4.1/IO.html#method-c-new 

读取档案内容:

file = File.open("foo.txt") 
doc = file.read("foo.txt")

写入档案:

File.open("bar.txt", "w+") do |f| 
 f << "aaa" 
 f << "
" 
 f << "bbb" 
end
 ios << obj → iosclick to toggle source

String Output—Writes obj to iosobj will be converted to a string using to_s.


 Ruby allows the following open modes:

https://ruby-doc.org/core-2.4.1/IO.html#method-c-new 

"r" Read-only, starts at beginning of file (default mode).
"r+" Read-write, starts at beginning of file.
"w" Write-only, truncates existing file
to zero length or creates a new file for writing.
"w+" Read-write, truncates existing file to zero length
or creates a new file for reading and writing.
"a" Write-only, each write call appends data at end of file.
Creates a new file for writing if file does not exist.
"a+" Read-write, each write call appends data at end of file.
Creates a new file for reading and writing if file does
not exist.

 


题目 29

请打开 todos.txt,其中每一行就是一个待办事项。
请编写一个程序,可以新增和删除代办事项,最后可以存盘离开。
重新执行这只程序,可以继续上次的代办事项。

注意:gets 读到的字符串,最后都会有一个换行符号,这是一个萤幕不可见的字符,在字符串中用 " "表示。用 chomp 方法可以去除字符串前后的空白和换行符号 ""

答案:

# 简易 Todo 代办事项应用
text = File.read("todos.txt")
todos = []
text.each_line do |line|     #each_line 是IO文件的method!,数组没有这个方法。
  todos << line.chomp
end

todos.each_with_index do |todo, index|
  puts "#{index}: #{todo}"
end

while (true)
  print "请输入指令 1. add 2. remove 3. save,然后按 Enter: "
  command = gets.chomp

  if command == "add"
    print "请输入代办事项: "
    new_event = gets.chomp      #把新的输入附加到数组todos最后,用 <<
    todos << new_event
  elsif command == "remove"
    print "请输入要删除的编号: "
    code = gets.chomp.to_i         #这里没有加入条件判断,如果没有输入正确编号从新输入
    todos.delete_at(code)
  elsif command == "save"
    puts "存盘离开"                      # 原理,用W+删除原文档内容,把todos[]存入文档。
    File.open("todos.txt", "w+") do |f|
      todos.each do |line|
        f << line
        f << " "
      end
    end
    break;
  else
    puts "看不懂,请再输入一次"
  end
end

 备注:之后我git push origin,成功后打开git网页, creat pull request. 最后看了一下别的同学的做法。上交了作业。


原文地址:https://www.cnblogs.com/chentianwei/p/8228377.html