Qyouu
在大多数情况下,这是首选方法: File.open(yourfile, 'w') { |file| file.write("your text") }当将一个块传递给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您可以在文档中找到它: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;}