遍历文件夹,获取文件夹下和子文件夹下所有扩展名为.png类型的文件名

遍历文件夹,获取文件夹下和子文件夹下所有扩展名为.png类型的文件名

方法非常多,其中一种是用标准库里的Find模块:
[code="ruby"]require 'find'

def find_all_png(dir)
files = []
Find.find(dir) do |path|
if File.extname(path) =~ /.png/i && File.file?(path)
yield path if block_given?
files << path
end
end
files
end[/code]
用的时候用一个关联block来做处理,像是输出当前目录及子目录下的所有png文件路径:
[code="ruby"]find_all_png('.') {|path| puts path }[/code]
或者不提供关联block也行,这个函数会返回包含符合条件的文件路径的数组。如果是要文件名而不是路径名的话,那在得到path之后用File.basename(path)就能得到,像是:
[code="ruby"]find_all_png('.').map {|path| File.basename path }[/code]

当然自己写递归函数来遍历文件夹也是可以的,只是标准库里有的东西一般就懒得重复写了。

[code="ruby"]
require 'find'
pngs=[]
Find.find(dir) do |path|
if File.directory?(path)
if File.basename(path)[0]==?.
File.prune
else
next
end
else
pngs<<path if File.basename(path)=~/.png$/i
end
end
[/code]