Backing Up to Versioned Filenames
class File
def File.versioned_filename(base, first_suffix='.0')
suffix = nil
filename = base
while File.exists?(filename)
suffix = (suffix ? suffix.succ : first_suffix)
filename = base + suffix
end
return filename
end
end
5.times do |i|
name = File.versioned_filename('filename.txt')
open(name, 'w') { |f| f << "Contents for run #{i}" }
puts "Created #{name}"
end
Related examples in the same category