データベースからデータを読み出して、テキストファイルに保存する必要があります。
Rubyではどのようにすればよいのでしょうか?Rubyにはファイル管理システムはありますか?
ほとんどの場合、これが望ましい方法です。
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
ドキュメント]1に記載されています。
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;
}