20
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Ruby]IO、File、Dirクラスのメソッド

Last updated at Posted at 2018-01-26

1年くらい前にRubyの勉強のためにIO、File、Dirクラスの便利メソッドをまとめたもの

参考
パーフェクトRuby

ファイルの読み込み

IO#open:ファイルを開く
IO#close:ファイルを閉じる
IO#read:ファイルの内容を末尾まで読み込む。読み込むバイト数の指定も可能
IO#gets:ファイルを1行ずつ読み込む

# 例:read
File.open('sample.txt') do |file|
    puts file.read  
end

# 例:gets
File.open('sample.txt') do |f|
    while line = f.gets
        puts line
    end
end

# each_lineを使いより自然な記述へ
File.open('sample.txt') do |f|
    f.each_line do |line|
        puts line
    end
end

ファイルの書き込み

IO#write
文字列を書き込む

File.open('sample.txt') do |f|
    f.write 'Ruby' # ファイルに"Ruby"と書き込む
end

アクセス位置の操作

IO#rewind
アクセス位置を先頭に戻す

IO#seek、IO#pos=
任意の位置に移動する

ファイルのロック

File#flock
ファイルをロックしたりロックを開放するメソッド

ファイルに関する情報の取得

File#atime:最後にアクセスした日時
File#ctime:最後に状態を変更した日時
File#mtime:最後に更新した日時
File#size:ファイルサイズ

ファイル操作

File#rename:ファイル名の変更/移動
File#unlink:ファイルの削除
File#symlink:ファイルのシンボリックリンク作成
File#link:ファイルのハードリンク作成
File#symlink:ファイルのシンボリックリンク作成
File#chmod:ファイルモードの指定
File#chown:オーナー・グループの変更

ファイルパス操作

File#dirname:ファイルのディレクトリパス
File#basename:ファイル名
File#extname:拡張子
File#join:ファイルパスの連結
File#split:dirnameとbasenameの配列
File#expend_path:相対パスから絶対パスを取得する

ファイル一覧の取得

Dir#entries:ディレクトリに含まれるファイル一覧の取得

ディレクトリ操作

Dir#mkdir:ディレクトリ作成
Dir#chdir:ディレクトリの移動
Dir#rmdir:ディレクトリの削除
Dir#exist?:ディレクトリの存在検査

20
9
1

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
20
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?