Tod*_*d R 909
您在寻找以下内容吗?
File.open(yourfile, 'w') { |file| file.write("your text") }
Run Code Online (Sandbox Code Playgroud)
Séb*_*nec 612
您可以使用简短版本:
File.write('/path/to/file', 'Some glorious content')
Run Code Online (Sandbox Code Playgroud)
它返回写入的长度; 请参阅:: write以获取更多详细信息和选项.
要附加到文件,如果它已经存在,请使用:
File.write('/path/to/file', 'Some glorious content', mode: 'a')
Run Code Online (Sandbox Code Playgroud)
Tom*_*art 244
在大多数情况下,这是首选方法:
File.open(yourfile, 'w') { |file| file.write("your text") }
Run Code Online (Sandbox Code Playgroud)
传递一个块File.open时,当块终止时,File对象将自动关闭.
如果未传递块File.open,则必须确保文件已正确关闭且内容已写入文件.
begin
file = File.open("/tmp/some_file", "w")
file.write("your text")
rescue IOError => e
#some error occur, dir not writable etc.
ensure
file.close unless file.nil?
end
Run Code Online (Sandbox Code Playgroud)
您可以在文档中找到它:
static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass)
{
VALUE io = rb_class_new_instance(argc, argv, klass);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, io, io_close, io);
}
return io;
}
Run Code Online (Sandbox Code Playgroud)
jdl*_*jdl 175
Ruby的文件类会给你的插件和出局::new和::open但其父的IO类,进入的深度#read和#write.
mvn*_*aai 113
File.open("out.txt", '<OPTION>') {|f| f.write("write your stuff here") }
Run Code Online (Sandbox Code Playgroud)
你的选择<OPTION>是:
r- 只读.该文件必须存在.
w - 创建一个空文件进行写入.
a - 附加到文件.如果文件不存在,则创建该文件.
r+ - 打开文件以更新读取和写入.该文件必须存在.
w+ - 为读取和写入创建一个空文件.
a+ - 打开文件进行阅读和追加.如果文件不存在,则创建该文件.
在你的情况下,w是优选的.
l3x*_*l3x 31
对于我们这些通过实例学习的人......
将文本写入文件,如下所示:
IO.write('/tmp/msg.txt', 'hi')
Run Code Online (Sandbox Code Playgroud)
奖金信息......
像这样读回来
IO.read('/tmp/msg.txt')
Run Code Online (Sandbox Code Playgroud)
通常,我想将文件读入我的剪贴板***
Clipboard.copy IO.read('/tmp/msg.txt')
Run Code Online (Sandbox Code Playgroud)
有时候,我想把剪贴板中的内容写成文件***
IO.write('/tmp/msg.txt', Clipboard.paste)
Run Code Online (Sandbox Code Playgroud)
***假设您已安装剪贴板gem
请参阅:https://rubygems.org/gems/clipboard
Mar*_*jic 22
要销毁文件的先前内容,请将新字符串写入文件:
open('myfile.txt', 'w') { |f| f << "some text or data structures..." }
Run Code Online (Sandbox Code Playgroud)
要附加到文件而不覆盖其旧内容:
open('myfile.txt', "a") { |f| f << 'I am appended string' }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
566356 次 |
| 最近记录: |