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
相关推荐
Sirens.2 小时前
Java异常处理解析:从防御式编程到自定义异常类
java·开发语言·笔记·学习·github·javac
lsx2024062 小时前
MySQL 运算符
开发语言
逆境清醒2 小时前
python教程总目录(更新中ing。。。)
开发语言·python
小北方城市网2 小时前
GEO 智变新篇:质效双升 + 责任共生,打造 AI 时代本地商业长效增长引擎
大数据·人工智能·python·数据库架构
CC.GG2 小时前
【Qt】常用控件----显示类控件(QLabel、QLCDNumber、QProgressBar、QCalendarWidget)
开发语言·数据库·qt
程芯带你刷C语言简单算法题2 小时前
Day43~实现一个算法求一个数字的树根
c语言·开发语言·算法·c
Hello_wshuo2 小时前
锅炉温控系统优化
linux·python·物联网
Chase_______2 小时前
【JAVA基础指南(四)】快速掌握类和对象
java·开发语言
KiefaC2 小时前
【C++11】包装器及其应用
开发语言·c++
weixin_470740362 小时前
python生成环境部署
开发语言·python