Ruby/File Directory/exist

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

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

Содержание

Checking If a File Exists

puts "It exists!" if File.exist?("file1.txt")



Checking to See if a File Exists

filename = "a_file.txt"
File.file? filename                        # => false
require "fileutils"
FileUtils.touch(filename)
File.file? filename                        # => true



Check to see if a dicectory exists

directory_name = "a_directory"
FileUtils.mkdir(directory_name)
File.file? directory_name                    # => false
File.exists? directory_name                  # => true



Create class to wrap File.exist and File.new method

class MyFile
  attr_reader :handle
  def initialize(filename)
    if File.exist?(filename)
      @handle = File.new(filename, "r")
    else
      return false
    end
  end
end