Backing Up to Versioned Filenames : write « File Directory « Ruby






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

1.opens text.txt for reading and writing, and changes the first character of the first line to X.