From: why the lucky stiff Date: 2005-08-19T03:25:07+09:00 Subject: Re: Idiomatic ruby version of this code? 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