---
title: "很棒的目录递归处理"
author: "nnnnon"
date: "2010-11-03T21:54:36Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-11-03T21:54:36Z"
id: 802187
url: "https://malijun.iteye.com/blog/802187"
---

原来一直是通过自己实现递归调用来处理目录，今天在《RubyProgramming》一书中看到，在ruby中居然是有专门的库“find.rb”来实现这个功能的，非常强大。

一个例子代码：


```ruby

require "find"


IGNORES = [/^\./] #以.开头的目录不进行处理

def listdir(top)
   Find.find(top){ |path|
      if FileTest.directory?(path)
          dir,base = File.split(path)
          IGNORES.each{ |re|
	     if re =~ base
	       Find.prune    #和next相比是整个目录都不处理，而next则对子目录还是进行处理
	      end
	  }
	  puts "目录："<<path
       else
          puts "文件："<<path
	  puts "文件名：" <<File.basename(path)
	  if File.basename(path).downcase! =~/\.jpg$/ #判断后缀名是否是jpg
	     puts "文件是图片"
	   end
       end

   }
end

listdir(ARGV[0])


```