萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 遞迴遍歷資料夾四種寫法:基礎遞迴、Dir.entries、Python 對照、Find 模組最優雅

寫法一:手動遞迴 + 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
copyright © 萬盛學電腦網 all rights reserved