From: Robert Klemme Date: 2011-01-20T21:32:02+09:00 Subject: Re: sorting songs to directories On Thu, Jan 20, 2011 at 9:48 AM, Mikhail Slyusarev wrote: > I've got a bunch of music that is in one directory and I wanted to sort > it so I wrote a ruby program to do it. The program basically works, just > for some reason it misses a few files, throwing TagLib2's 'BadFile' > exception. However, if I run it twice (just sorting the files it missed) > it will sort those files correctly. There are more details in the > comments of the attached file. > > Help would be sincerely appreciated. Thank you. > > Attachments: > http://www.ruby-forum.com/attachment/5766/main.rb Just a quick check but your regexp for matching songs in line 21 is broken (you don't anchor so it will match anywhere). Also you don't need a capturing group since you don't do anything with the matched portion. This should be better: elsif /\.(?:mp3|mp4|wma|flac|ogg|ape|wav|vox|aac|m4p|3gp|m4a)\z/i =~ song Few more remarks. Line 16: don't do that, it's hard to read and easy to miss that the last one is actually a Hash. Line 29: if you make "artists" a Set or Hash you don't need this and it's more efficient. The whole approach seems overly complicated to me. I'd rather do UNKNOWN = "Unknown Type".freeze workingDir = ... Dir.chdir workingDir Dir["*"].each do |f| next if File.directory? f dir = TagLib2::File.new(f).artist rescue UNKNOWN # deal with the case that there is a non directory # with this name until File.directory? dir Dir.mkdir dir rescue (dir << "_") end FileUtils.mv f, dir end Isn't this basically what your script does? Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/