From: Robert Klemme Date: 2010-10-20T16:39:23+09:00 Subject: Re: Removing files if those exists On Wed, Oct 20, 2010 at 9:16 AM, Josh Cheek wrote: > On Wed, Oct 20, 2010 at 1:54 AM, Simo M. wrote: > >> Hi, >> >> I just started to work with ruby and I do not know how to do this. >> >> So I have files junk1.cs, junk2.cs, junk3.cv etc. in the same folder. >> There is also other files in the same folder that cannot be deleted. >> >> What I would like to do is >> >> If file junk*.cs exist >>  - remove all junk*.cs files from dir >> >> Thanks in advance. >> >> -- >> Posted via http://www.ruby-forum.com/. >> >> > First select them using Dir[] (you can try to get fancy with a pattern here, > but I don't think there is a way to specify multiple digits, so something > like junky.cs would get picked up by a "junk*.cs" and "junk[0-9].cs" > wouldn't pick up junk11.cs, so I'd just use "*" for the pattern. > http://ruby-doc.org/core/classes/Dir.html#M002323 > > Then, use the grep method to select the ones you want, since we didn't use > the pattern above. You'll have to give it a regexp, if you aren't familiar > with that, you can just use /\Afile\d+\.cs\Z/ and change out the name and > extension as necessary. It basically says if the string begins with "file", > followed by one or more digits, followed by ".cs" and nothing else, then it > is a match. > http://ruby-doc.org/core/classes/Enumerable.html#M003121 > > Then use each to iterate over the list of file names > http://ruby-doc.org/core/classes/Array.html#M002173 > > And pass them to File.delete > http://ruby-doc.org/core/classes/File.html#M002536 If you drop explicit matching of digits there is a much easier approach: 09:36:22 test$ touch junk1.cs junk2.cv 09:36:23 test$ irb19 Ruby version 1.9.1 irb(main):001:0> f = Dir["junk*.c[sv]"] => ["junk1.cs", "junk2.cv"] irb(main):002:0> File.unlink *f => 2 irb(main):003:0> Dir["junk*.c[sv]"] => [] irb(main):004:0> Or as one liner File.unlink(*Dir["junk*.c[sv]"]) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/