如果你想保存到一个文件,你需要做的就是打开文件,写入它,然后关闭它:
File.open("myFileName.txt", "a") do |mFile|
mFile.syswrite("Your content here")
mFile.close
end
使用时open
,如果文件不存在,您将创建该文件。
需要注意的一件事是打开文件有不同的方法,这些方法将决定程序写入的位置。"a"
表示它会将您写入文件的所有内容附加到当前内容的末尾。
以下是一些选项:
r Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode.
r+ Read-write mode. The file pointer will be at the beginning of the file.
w Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
因此,在您的情况下,您需要提取要保存的数据,然后将其写入文件,如我所示。您还可以通过执行以下操作指定文件路径:
File.open("/the/path/to/yourfile/myFileName.txt", "a") do |mFile|
mFile.syswrite("Your content here")
mFile.close
end
要注意的另一件事是它open
不会创建目录,因此您需要自己创建目录,或者您可以使用您的程序来创建目录。这是一个有助于文件输入/输出的链接:
http://www.tutorialspoint.com/ruby/ruby_input_output.htm