LoginSignup
84
62

More than 5 years have passed since last update.

rubyでFile.openを使わずにファイルの読み書きをする方法

Posted at

File.readとかFile.writeみたいな便利なメソッドが用意されているので、遠慮なくそれを使う。

pry(main)> File.write('hoge.txt', 'ok')
=> 2
pry(main)> File.read('hoge.txt')
=> "ok"

想定してる状況

ファイル読み込んでいろいろ書き換えて別のファイルに保存したいって時に、

File.open('hoge.csv') do |out_f|
  File.open('hoge.txt') do |in_f|
    out_f.write in_f.read.gsub("¥s", ',')
  end
end

と書いてもいいけど、

File.write 'hoge.csv', File.read('hoge.txt').gsub("¥s", ',')

みたいにさっくりも書ける。便利。

余談

File.openでFileオブジェクト取得したら、readメソッドで中身のテキストを取得する事も出来る。

pry(main)> File.open('hoge.txt').read
=> "ok"

open-uri使った場合も同じようにreadでテキスト取得出来て、パッとリソース取得したい時には便利。

json = open("http://b.hatena.ne.jp/entry/json/#{url}").read
84
62
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
84
62