module Find
Find 模块支持文件路径集合的自顶向下遍历。
例如,计算你的主目录下的所有文件的大小,忽略“点”(dot)目录(例如 $HOME/.ssh)中的任何内容。
require 'find' total_size = 0 Find.find(ENV["HOME"]) do |path| if FileTest.directory?(path) if File.basename(path).start_with?('.') Find.prune # Don't look any further into this directory. else next end else total_size += FileTest.size(path) end end
Constants
- VERSION
-
版本字符串
Public Class Methods
Source
# File lib/find.rb, line 41 def find(*paths, ignore_error: true) # :yield: path block_given? or return enum_for(__method__, *paths, ignore_error: ignore_error) fs_encoding = Encoding.find("filesystem") paths.collect!{|d| raise Errno::ENOENT, d unless File.exist?(d); d.dup}.each do |path| path = path.to_path if path.respond_to? :to_path enc = path.encoding == Encoding::US_ASCII ? fs_encoding : path.encoding ps = [path] while file = ps.shift catch(:prune) do yield file.dup begin s = File.lstat(file) rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG, Errno::EINVAL raise unless ignore_error next end if s.directory? then begin fs = Dir.children(file, encoding: enc) rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG, Errno::EINVAL raise unless ignore_error next end fs.sort! fs.reverse_each {|f| f = File.join(file, f) ps.unshift f } end end end end nil end
Source
# File lib/find.rb, line 86 def prune throw :prune end
跳过当前文件或目录,并从下一项重新开始循环。如果当前文件是目录,则不会递归进入该目录。仅在与 关联的块中有意义。Find::find
有关示例,请参见 Find 模块文档。
私有实例方法
Source
# File lib/find.rb, line 41 def find(*paths, ignore_error: true) # :yield: path block_given? or return enum_for(__method__, *paths, ignore_error: ignore_error) fs_encoding = Encoding.find("filesystem") paths.collect!{|d| raise Errno::ENOENT, d unless File.exist?(d); d.dup}.each do |path| path = path.to_path if path.respond_to? :to_path enc = path.encoding == Encoding::US_ASCII ? fs_encoding : path.encoding ps = [path] while file = ps.shift catch(:prune) do yield file.dup begin s = File.lstat(file) rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG, Errno::EINVAL raise unless ignore_error next end if s.directory? then begin fs = Dir.children(file, encoding: enc) rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG, Errno::EINVAL raise unless ignore_error next end fs.sort! fs.reverse_each {|f| f = File.join(file, f) ps.unshift f } end end end end nil end
Source
# File lib/find.rb, line 86 def prune throw :prune end
跳过当前文件或目录,并从下一项重新开始循环。如果当前文件是目录,则不会递归进入该目录。仅在与 关联的块中有意义。Find::find
有关示例,请参见 Find 模块文档。