Comparing Directories Ruby Style

Filed Under (Ruby) by manatarms on 08-10-2007

Tagged Under :

I recently needed to recursively compare 2 directories by filename. Here’s the solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
require 'ftools'
srcDir = "/home/Music/"
destDir = "/home/Music/iTunes/iTunes Music"
 
mHash = Hash.new
iHash = Hash.new
 
#Add all files to hash
Dir[srcDir + '/**/*.mp3'].each do |path|    
    mHash[path.split('/').last] = pathend
 
    #Add all files to second hash
    Dir[destDir + "/**/*.mp3"].each do |path|    
        iHash[path.split('/').last] = path
    end
 
puts "Source # Files: " + mHash.length.to_sputs "Dest # Files: " + iHash.length.to_s
 
#Compare Hashes and copy Any data
 Hash.each_key do |key|
    if iHash[key] == nil  
        puts "Copying " + mHash[key] +" to " + destDir
        File.copy(mHash[key],destDir+"/")   
    end
end

Leave a Reply