From: forgottenwizard Date: 2007-10-22T05:52:41+09:00 Subject: Re: Problem using FileUtils to sort JPEG files On 15:41 Sun 21 Oct , 7stud -- wrote: > 1) pix is already a string, so doing this: > > #{pix}" > > is unnecessary. I do that in places to make sure there isn't a problem somewhere with a command taking a wrong arg. Unneeded it may be, but it makes me feel better when I'm debugging. > 2) The following causes a syntax error: > > If File.directory?(filetype) then > > To see a similar syntax error, try this: > > num = 10 > If num == 10 > print 'yes' > end > Do you have a better suggestion? I was thinking of moving that outside of the for loop and only doing it once, but looping through everything twice (once to check to see if the directories exist and/or make them, and a second to sort), but leaving it in makes a little more sense to me. Can you help explain the exact error, or is it just saying that the directory is already there? > 3) Your default loop probably should be each(), unless you have a > specific reason to use another loop: > > Dir.glob("*.{jpeg,jpg,png}").each do |fname| > > A for-loop has a different scope than each(), i.e. it does not create a > new scope. An each() loop creates a new scope, although it is leaky(see > example below). > > That comes from using bash/C before. I'll look into trying it with each soon. > 4) I couldn't find any documentation for the RMagick format() method, > which is pretty typical of the horrible ruby documentation, however this > works error free for me: > > require 'fileutils' > > Dir.chdir("../some_dir") > workdir = Dir.pwd #outside of each block > > Dir.glob("*.{jpeg,jpg,png}").each do |fname| > filetype = fname.split(".")[-1] > > if File.directory?(filetype) > FileUtils.move(fname, "#{workdir}/#{filetype}") #workdir is > accessible inside each() > else > Dir.mkdir(filetype) > FileUtils.move(fname, "#{workdir}/#{filetype}") > end > end Except if a file (we'll call it image) is in the dir, it won't get sorted, which is why I'm usin RMagick in the first place. I never fully trusted just relying on extensions. And yes, I do notice the flaw in my logic here, and I'm going to correct it within Dir.glob now :)