How to check if a directory / file / symlink exists with a single command in Ruby

Is there one way to detect if directory / file / symlink / etc. entity (more generalized) exists?

I need one function because I need to check an array of paths, which can be directories, files or symbolic links. I know that File.exists?"file_path" works for directories and files, but not for symbolic links (is it File.symlink?"symlink_path" ).

+48
ruby file directory exists symlink
Feb 04 2018-11-11T00:
source share
2 answers

The standard file module has regular test files :

 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: "Thank you, but I need all three true or false."

Obviously not. So 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 
+100
Feb 04 2018-11-14T00:
source share
— -

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

+11
Feb 04 '11 at 11:52
source share