ファイル入出力 (Ruby)
[履歴] [最終更新] (2016/03/03 22:47:59)
プログラミング/IoT の関連商品 (Amazonのアソシエイトとして、当メディアは適格販売により収入を得ています。)
最近の投稿
注目の記事

読み込み

sample.rb

File.open("in.txt",'r:UTF-8'){|f| # r: 読み込み (省略可),
                            # r:Shift_JISなどとすればエンコーディング指定可能
  puts f.read
}

File.open("in.txt"){|f|
  f.each_line do |line|
    puts line
  end
}

File.open("in.txt"){|f|
  f.each_char do |char|
    print char
  end
}

File.open("in.txt"){|f|
  f.each_byte do |byte|
    print byte
  end
  puts
}

f = File.open("in.txt")
p f.readline
f.each_char do |char|
  print char
end
f.close

in.txt

First line.
Second line.

出力例

$ ruby sample.rb 
First line.
Second line.
First line.
Second line.
First line.
Second line.
701051141151163210810511010146108310199111110100321081051101014610
"First line.\n"
Second line.

読み込み (ARGF)

sample.rb

ARGF.each_line do |line|
  print line.gsub(/line/, 'sentence')
end

in.txt

First line.
Second line.

in2.txt

Third line.
Fourth line.

出力例

$ ruby sample.rb in.txt in2.txt
First sentence.
Second sentence.
Third sentence.
Fourth sentence.

書き込み

File.open("out.txt", 'w'){|f|  # w:書き込み, a:追記
                               # w:Shift_JISなどとすればエンコーディング指定可能
  f.puts "hi"
}

(補足)

... {|f|
  ...
}

という部分は、すべて

... do |f|
  ...
end

と記載可能です。

関連ページ