05
Sep
09

small enhancements to ruby’s find tools



Here’s a method I find very useful for searching files :

  1. require "find"
  2.  
  3. module Finder
  4.  
  5.     # select files that return true from block
  6.     def Finder.select_files(obj={})
  7.         # results list
  8.         results = []
  9.         # directory to scan
  10.         dir = obj[:dir] || "."
  11.         # whether or not we should display everything
  12.         # we’re doing
  13.         verbose = obj[:verbose] || false
  14.         # a block is very important 🙂
  15.         if !block_given?
  16.             puts "warning:no block given"
  17.             # we return an empty list
  18.             return results
  19.         end
  20.         # we make an absolute path so that every file generated
  21.         # will be absolute too
  22.         Find.find(File.expand_path dir) do |file|
  23.             puts "Iterating over #{file}" if verbose
  24.             # see if we need to select the file
  25.             res = yield(file)
  26.             if res
  27.                 puts "Selecting #{file}" if verbose
  28.                 results << file
  29.             end
  30.         end
  31.         return results
  32.     end
  33.    
  34. end

Here’s how you could use this to select files matching given extensions:

  1. require "finder"
  2.  
  3. extensions = [".txt",".ini"]
  4. files = Finder.select_files(:dir => "yourdir") {|f| extensions.include? File.extname(f) }

You could select files that match a given pattern :

  1. require "finder"
  2.  
  3. # this will select all files that have PingPong in the name
  4. files = Finder.select_files(:dir => "whatever") {|f| f=~/PingPong/}
  1. require "finder"
  2.  
  3. # an example showing the verbose parameter
  4. # if you pass this, you will see all the files the method
  5. # is iterating over, and it will also output a message when
  6. # it selects a file
  7. files = Finder.select_files(:dir => "whatever",:verbose => true) {|f| f=~/woireowurwoiu/}

Advertisements

0 Responses to “small enhancements to ruby’s find tools”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Blog Stats

  • 229,426 hits

%d bloggers like this: