LoginSignup
14
8

More than 5 years have passed since last update.

Rubyでファイルに追記をする方法

Posted at

Rubyでちょっとしたログをファイルの最後にどんどん追加したかったのですが、File.openのモードを指定するだけで簡単に書けました。

File.openのモード指定

ファイルの最後の行に書き込みをするためにはFile.openモードの’a’を指定します。

まずテストファイルを用意して

test.txt
foo
bar

モードにaを指定して開く。

main.rb
file = File.open('path/to/test.txt','a')

3.times { |n|
  file.puts "text #{n}"
}

file.close

ファイルを確認すると

test.txt
foo
bar
text 0
text 1
text 2

無事末尾に記入されてます。

参照

14
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
8