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
相关推荐
这个人懒得名字都没写2 小时前
Python包管理新纪元:uv
python·conda·pip·uv
有泽改之_2 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
是毛毛吧3 小时前
边打游戏边学Python的5个开源项目
python·开源·github·开源软件·pygame
暮乘白帝过重山3 小时前
ArkTS ForEach 参数解析:组件与键值生成器
开发语言·数据库
LiamTuc3 小时前
Java构造函数
java·开发语言
三途河畔人3 小时前
Pytho基础语法_运算符
开发语言·python·入门
Benmao⁢3 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
adsadswee3 小时前
Qt 样式与 QLinearGradient 渐变详解
开发语言·qt·qt样式表·qlineargradient·qss渐变效果
花月C4 小时前
个性化推荐:基于用户的协同过滤算法
开发语言·后端·算法·近邻算法
脾气有点小暴4 小时前
前端页面跳转的核心区别与实战指南
开发语言·前端·javascript