寫法一:手動遞迴 + Dir.foreach
def traverse(path)
if File.directory?(path)
Dir.foreach(path) do |entry|
next if entry == "." || entry == ".."
traverse(File.join(path, entry))
end
else
puts "File: #{File.basename(path)}, Size: #{File.size(path)}"
end
end
traverse("D:/apache-tomcat")
寫法二:Dir.entries + 視覺化縮排
def list_tree(path, indent=0)
Dir.entries(path).each do |entry|
next if entry == "." || entry == ".."
full = File.join(path, entry)
if File.directory?(full)
puts "#{' '*indent}[#{entry}]"
list_tree(full, indent+1)
else
puts "#{' '*indent}|--#{entry}"
end
end
end
list_tree(".")
寫法三:Python 對照 (os.walk)
import os
def get_files(dir):
for root, _, files in os.walk(dir):
for f in files:
yield os.path.join(root, f)
for f in get_files("D:/workspace"):
print(f)
寫法四:Find 模組 (推薦,最簡潔)
require 'find'
Find.find("/home/bruce") do |path|
puts path if File.file?(path)
end
# 一行版
Find.find(".") { |f| puts f if File.file?(f) }
效能與風格比較
| 寫法 | 優點 | 缺點 | 推薦度 |
| 手動遞迴 | 完全控制邏輯 | 冗長、易漏處理 . / .. | ⭐⭐ |
| Dir.entries 遞迴 | 直觀、可自訂輸出格式 | 仍需手動遞迴 | ⭐⭐⭐ |
| Python os.walk | 生成器、記憶體友善、標準庫 | 非 Ruby 原生 | ⭐⭐⭐⭐ (Python 專案) |
| Find.find | 內建遞迴、支援 prune、區塊語法極簡 | 無法直接控制遍歷順序 | ⭐⭐⭐⭐⭐ (Ruby 首選) |
進階:排除目錄、只列特定副檔名
require 'find'
EXCLUDE = %w[.git node_modules tmp]
EXTS = %w[.rb .yml .md]
Find.find(".") do |path|
# 排除目錄
if File.directory?(path)
base = File.basename(path)
Find.prune if EXCLUDE.include?(base)
next
end
# 過濾副檔名
puts path if EXTS.include?(File.extname(path))
end