From: Daniel Berger Date: 2005-08-19T03:31:41+09:00 Subject: Re: Idiomatic ruby version of this code? why the lucky stiff wrote: > Brock Weaver wrote: > >> Here's my first solution: >> >> Dir.new("./").each do |file| >> if file.match(/mp3$/) >> File.rename(file, file.gsub(/mp3$/, 'temp')) >> elsif file.match(/temp$/) >> File.rename(file, file.gsub(/temp$/, 'mp3')) >> end >> end >> > > You could use the tertiary operator to switch file names, but the (exp > .. and .. or) is also nice for this kind of swapping thing. > > Dir["*.{temp,mp3}"].each do |file| > File.rename( file, file.gsub( /\w+$/ ) { |ext| ext == 'mp3' and > 'temp' or 'mp3' } ) > end > > If you don't want your extensions hardcoded everywhere, use an array: > > exts = ['temp', 'mp3'] > Dir["*.{#{exts.join ','}}"].each do |file| > File.rename( file, file.gsub( /(\w+)$/ ) { exts.detect { |x| x != $1 > } } ) > end > > _why > > gsub and backreferences? Why take that approach when File.basename is available? def switch(old, new) Dir["*.#{old}"].each{ |file| new_name = File.basename(file, old) + "." + new File.rename(file, new_name) } end Regards, Dan