From: "David A. Black" Date: 2008-06-10T14:31:20+09:00 Subject: Re: Working with arrays Hi -- On Tue, 10 Jun 2008, Clement Ow wrote: > Hi, people I know some of ya might find me familiar but, I really am > still a novice in ruby thus i'll need help once in awhile. I'd > defeinitely appreciate whatever help that is rendered! =) > > ok, so back to our topic. I have a code where I would like to traverse > into files and folders and then at the same time pass in exceptions and I think you mean extensions, not exceptions. > then after that select the whole load of files to carry out actions like > copying or deleting. But I'll only need help for the traversing of > folders and the exceptions part. Here's my code: > > src1 = [] > $source.each do |y| > Find.find(y + "/") do |file| > src1 << file > $file_exception[i].each do |ex| What is i? > src1.delete_if {|x| /#{ex}/ =~ File.basename(file)} > > end > end > $source is an array of source paths like ["C:/Del", "C:/My Pictures"] > $file_exception is an array of exceptions like [".txt", ".xls"] > > The whole block of code is working fine except that it traverses into > the folders twice, and then parses all the file paths into src1(which is > not what is wanted) Is there any way to improve on my code? First, don't use global variables. They don't play nicely with encapsulated code (i.e., code where knowledge and behavior is encapsulated in objects which have to talk to each other, in an orderly fashion, to get things done). Second, I'd use File.extname rather than a pattern match on File.basename. Something like this (semi-tested only): source = %w{ C:/Del C:/My\ Pictures } extensions = %w{ .txt .xls } files = [] source.each do |s| Find.find(s) do |file| next if extensions.include?(File.extname(file)) files << file end end David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin ADVANCING WITH RAILS July 21-24 Edison, NJ See http://www.rubypal.com for details and updates!