Help us understand the problem. What is going on with this article?

PHPerがつまづいたRubyの仕様

More than 3 years have passed since last update.

スクリプトの実行ログとしてファイルへの書き込みをしたい時。
PHPだと

$fp = fopen('/var/tmp/hoge.txt', 'w');
while(true) {
    // action
    fwrite($fp, 'actionのログ');
}
fclose($fp);

みたいにやっていた。
細かいところはおいておいて、tail -f /var/tmp/hoge.txt とかで回しておけば、どんぐらい進んだかが一目瞭然。

で、同じような感覚で ruby で書いてみた

fp = File.open('/var/tmp/hoge.txt', 'w')
list.each do |val|
  # action
  fp.write('actionのログ')
end
fp.close

ログがつらつら流れることを期待して tail -f /var/tmp/hoge.txt を叩いてみる。
が、流れてこない。
で、処理が全部終わったらドカッとログが出現。
ということは、ruby だと close するまでは実際にはファイルに書き込みをしないということか...

で、ちょいちょい調べてみたら

fp = File.open('/var/tmp/hoge.txt', 'w')
list.each do |val|
  # action
  fp.write('actionのログ')
  fp.flush
end
fp.close

のように flush メソッドを叩けばいけるらしい。なるほど...

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした