正确理解Ruby更新文件

作为一个优秀的编程人员,我们必须要不断的去学习新知识来补充我们的知识库,更新技术。Ruby语言就是一项新的编程语言,值得我们去深入学习。在这里我们将会了解到Ruby更新文件的一些操作技巧。#t#

Ruby更新文件

假设我们想要打开一个文件用于读和写,简单的加一个'+'号到file mode就行了:

 

  1. f1 = File.new("file1", "r+")   
  2. # Read/write, starting at 
    beginning of file.   
  3. f2 = File.new("file2", "w+")   
  4. # Read/write; truncate 
    existing file or create a new one.   
  5. f3 = File.new("file3", "a+")   
  6. # Read/write; start at 
    end of existing file or create a   
  7. # new one. 

Ruby更新文件中的追加一个文件

假设我们想要追加一段信息到一个存在文件,当我们打开文件时使用'a'作为file mode就行了:

 
 
 
  1. logfile = File.open
    ("captains_log", "a")   
  2. # Add a line at the 
    end, then close.   
  3. logfile.puts "Stardate 
    47824.1: Our show has
     been canceled."   
  4. logfile.close 

以上就是我们对Ruby更新文件的一些操作方法介绍。

THE END