From: Josh Cheek Date: 2010-10-20T16:16:58+09:00 Subject: Re: Removing files if those exists --001485f6299aca73d404930731be Content-Type: text/plain; charset=ISO-8859-1 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 --001485f6299aca73d404930731be--