How to write to file in Ruby?
This is preferred approach in most cases:
File.open(yourfile, 'w') { |file| file.write("your text") }
When a block is passed to File.open
, the File object will be automatically closed when the block terminates.
If you don't pass a block to File.open
, you have to make sure that file is correctly closed and the content was written to file.
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
You can find it in documentation:
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;}