Ruby递归目录文件的又一种方法

经常派得上用场,记录一下。

递归文件做一些操作

ruby 复制代码
#encoding:utf-8

require 'pathname'

def recursive_enum_files(from_path)
	from_path = Pathname.new(from_path)
	raise ArgumentError,'must start at a directory.' unless from_path.directory?
	from_path.enum_for(:find_files,from_path)
end

private def find_files(parent,&block)
	parent.children.sort
	parent.children.each do |child|
		if child.directory?
			find_files(child,&block)
		else
			yield child if block_given?
		end
	end
end

start_path = 'E:/abcdefg'
recursive_enum_files(start_path).each do |path|
	puts (File.size?(path)/1024.0/1024.0/1024.0).round(2).to_s + 'GB => ' + path # 列出文件大小
end

对文件夹做一些操作

ruby 复制代码
#encoding:utf-8

require 'pathname'

def recursive_enum_files(from_path)
	from_path = Pathname.new(from_path)
	raise ArgumentError,'must start at a directory.' unless from_path.directory?
	from_path.enum_for(:find_files,from_path)
end

private def make_total(s)
	return Proc.new { |i| s += i }
end

private def find_files(parent,&block)
	n = make_total(0)
	parent.children.each do |child|
		if child.directory?
			n.call(find_files(child,&block))
		else
			n.call(File.size?(child))
		end
	end
	yield parent,n.call(0) if block_given?
	n.call(0)
end

start_path = 'E:/abcdefg'
recursive_enum_files(start_path).each do |path,size|
	puts (size/1024.0/1024.0/1024.0).round(2).to_s + 'GB => ' + path.to_s if size >= 1024*1024*1024*5 # 大于5GB
end
相关推荐
Lenyiin几秒前
《LeetCode 顺序刷题》11 -20
java·c++·python·算法·leetcode·lenyiin
wuqingshun3141592 分钟前
说一下java的四种引用
java·开发语言
Jelena157795857924 分钟前
淘宝图搜API接口技术深度解析:从架构设计到工程实践
python·api
wjs20246 分钟前
Bootstrap4 图像形状
开发语言
枫叶丹41 小时前
【Qt开发】Qt界面优化(四)-> Qt样式表(QSS) 选择器概况
c语言·开发语言·c++·qt
郝学胜-神的一滴1 小时前
深入理解TCP连接的优雅关闭:半关闭状态与四次挥手的艺术
linux·服务器·开发语言·网络·tcp/ip·程序人生
yaoxin5211232 小时前
325. Java Stream API - 理解 Collector 的三大特性:助力流处理优化
java·开发语言
光泽雨8 小时前
C# 中 Assembly 类详解
开发语言·c#
少控科技9 小时前
C#基础训练营 - 02 - 运算器
开发语言·c#
瞎某某Blinder9 小时前
DFT学习记录[4] 电子和空穴的有效质量计算全流程
python·学习