1. 建立與寫入
File.open("222.rb", "w+") do |f|
f.puts "123\nwadwan12124124ndwdw"
end
2. 讀取並輸出 (區塊形式自動關閉)
File.open("222.rb", "r") do |f|
f.each_line { |line| puts line }
end
3. IO.foreach 直接逐行處理 (無需手動 open/close)
IO.foreach("222.rb") do |line|
puts line if line =~ /abc/ # 含 abc 的行
puts line if line !~ /qwe/ # 不含 qwe 的行
end
4. 取得絕對路徑
puts File.expand_path("222.rb") # C:/full/path/222.rb
5. 統計特定位元組出現次數
count = 0
File.open("222.rb", "rb") do |f|
f.each_byte { |b| count += 1 if b == ?1 } # ?1 = '1'.ord (49)
end
puts count
6. 檢查檔案存在並建立寫入
puts File.exist?("asd.txt") # false
File.open("asd.txt", "w") { |f| f.write("hehe\nhaha") }
puts File.exist?("asd.txt") # true
7. StringIO 記憶體檔案操作
require 'stringio'
ios = StringIO.new("abc\ndef\n123")
ios.seek(3) # 移至 'd' 前
ios.puts("xyz") # 覆寫 → "abc\nxyz\n123"
puts ios.tell # 當前位移
puts ios.string # 完整內容
puts ios.string.dump # 顯示跳脫序列 ("abc\nxyz\n123\n")
8. StringIO ungetc 回推字元
ios = StringIO.new("abc\ndef")
ios.seek(3) # 在 'd'
ios.ungetc(?w) # 將 'w' 推回 → 緩衝區變 "wdef"
puts ios.gets # "wdef\n"
puts ios.gets # nil (EOF)
9. 系統開啟檔案 (關聯程式)
# Windows
system("notepad #{path}")
# macOS
system("open #{path}")
# Linux (xdg-open 通用)
system("xdg-open #{path}")
10. 讀取第一行去換行
first_line = File.readlines(path)[0].chomp