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
相关推荐
偶尔贪玩的骑士10 分钟前
Kioptrix Level 1渗透测试
linux·开发语言·网络安全·php
それども22 分钟前
忽略Lombok构建警告
java·开发语言·jvm
qiuiuiu41344 分钟前
正点原子RK3568学习日志12-注册字符设备
linux·开发语言·单片机·学习·ubuntu
liu****1 小时前
20.哈希
开发语言·数据结构·c++·算法·哈希算法
MetaverseMan1 小时前
Java Spring 框架的`@Autowired` 注解 以及依赖注入分析
java·开发语言·spring
迎風吹頭髮1 小时前
Linux服务器编程实践58-getnameinfo函数:通过socket地址获取主机名与服务名
开发语言·数据库·php
爱和冰阔落1 小时前
【C++多态】虚函数/虚表机制与协变 、override和final关键字全解析
开发语言·c++·面试·腾讯云ai代码助手
码住懒羊羊1 小时前
【C++】stack|queue|deque
java·开发语言·c++
这里有鱼汤1 小时前
📊量化实战篇:如何计算RSI指标的“拥挤度指标”?
后端·python
一只专注api接口开发的技术猿1 小时前
容器化与调度:使用 Docker 与 K8s 管理分布式淘宝商品数据采集任务
开发语言·前端·数据库