如何使用Ruby中的一个命令检查目录/文件/符号链接是否存在 [英] How to check if a directory/file/symlink exists with one command in Ruby

查看:166
本文介绍了如何使用Ruby中的一个命令检查目录/文件/符号链接是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种检测目录/文件/符号链接/ etc的方法。实体(更广义)存在?



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

解决方案

标准文件模块具有通常的文件测试可用:

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

你应该能够找到你想要的东西。







OP:谢谢,但我需要所有三个真或假


显然不是。好的,尝试一下:

  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')#=>假


Is there a single way of detecting if a directory/file/symlink/etc. entity (more generalized) exists?

I need a single function because I need to check an array of paths that could be directories, files or symlinks. I know File.exists?"file_path" works for directories and files but not for symlinks (which is File.symlink?"symlink_path").

解决方案

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

这篇关于如何使用Ruby中的一个命令检查目录/文件/符号链接是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆