Ruby/File Directory/write

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

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



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

f = File.open("text.txt", "r+")
f.write "123456"
f.close