如何在 Ruby 中用一个命令检查目录/file/symlink 是否存在

有没有一种检测目录/file/symlink/etc 实体(更通用的)是否存在的方法?

我需要一个单一的函数,因为我需要检查一个路径数组,可能是目录,文件或符号链接。我知道 File.exists?"file_path"适用于目录和文件,但不适用于符号链接(即 File.symlink?"symlink_path")。

67992 次浏览

Why not define your own function File.exists?(path) or File.symlink?(path) and use that?

The standard File module has the usual file tests available:

RUBY_VERSION # => "1.9.2"
bashrc = ENV['HOME'] + '/.bashrc'
File.exist?(bashrc) # => true
File.file?(bashrc)  # => true
File.directory?(bashrc) # => false

You should be able to find what you want there.


OP: "Thanks but I need all three true or false"

Obviously not. Ok, try something like:

def file_dir_or_symlink_exists?(path_to_file)
File.exist?(path_to_file) || File.symlink?(path_to_file)
end


file_dir_or_symlink_exists?(bashrc)                            # => true
file_dir_or_symlink_exists?('/Users')                          # => true
file_dir_or_symlink_exists?('/usr/bin/ruby')                   # => true
file_dir_or_symlink_exists?('some/bogus/path/to/a/black/hole') # => false

Just File.exist? on it's own will take care of all of the above for you