Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

書籍 Ruby Cookbook | 最終更新日の取得

パンくず

Ruby Cookbook
最終更新日の取得

概要

最終更新日の取得

内容

variable = File.stat(<ファイル名>)
variable.mstat # => modified time

サンプル

# encoding: Windows-31J
require "pp"

def output_file_stat(filename)
  stat =  File.stat(filename)
  p stat.mtime
end

filename = "C:\\hoge\\hoge_writable.txt"
output_file_stat(filename)

sleep(2)

# ファイルに書き込み
open(filename, "w") do |f|
  f << "hoge"
end
output_file_stat(filename)
sleep(2)

# ファイルに追記
open(filename, "a") do |f|
  f << "hoge"
end
output_file_stat(filename)
sleep(2)

# ファイルから読み取り
open(filename) do |f|
  ret =  f.read
end
output_file_stat(filename)

出力

2012-07-15 00:26:27 +0900
2012-07-15 00:26:34 +0900
2012-07-15 00:26:36 +0900
2012-07-15 00:26:36 +0900