From: "Brian Schröder" Date: 2005-08-19T01:32:29+09:00 Subject: Re: Idiomatic ruby version of this code? On 18/08/05, Brock Weaver wrote: > Showing off ruby to a coworker, and I want to emphasize how succinct yet > clear it can be. So I want to rename all .mp3 files to .temp, or vice versa > in the current directory -- in the shortest LOC *that you would actually write*; > not the "here's a one-liner nobody in their right mind would every write if > they had to maintain it". > > 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 > > Note you can NOT do the following, as it renames mp3 to temp, > then immediately renames that same file back to mp3... > > Dir.new("./").each do |file| > File.rename(file, file.gsub(/mp3$/, 'temp')) if file.match(/mp3$/) > File.rename(file, file.gsub(/temp$/, 'mp3')) if file.match(/temp$/) > end > > Any ideas? > > -- > Brock Weaver > [OBC]Technique > > If it where a one time solution, I'd do something like this. Though maybe I'd extract the file endings into variables, to make it easier to change them. mp3 = Dir['*.mp3'] temp = Dir['*.temp'] mp3.each do | fn | File.rename(fn, File.basename(fn, '.mp3') + '.temp') end temp.each do | fn | File.rename(fn, File.basename(fn, '.temp') + '.mp3') end regards, Brian -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/