Backing Up to Versioned Filenames

2019-06-19 20:03栏目:技术创新

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

版权声明:本文由新浦京娱乐站_新浦京娱乐场官网_新浦京娱乐发布于技术创新,转载请注明出处:Backing Up to Versioned Filenames