如何检查Ruby中是否存在给定目录 [英] How to check if a given directory exists in Ruby
问题描述
我正在尝试编写一个脚本,该脚本根据指定目录是否存在自动检出或更新 Subversion URL.
I am trying to write a script which automatically checks out or updates a Subversion URL based on whether a specified directory exists or not.
出于某种原因,我的代码无法正常工作并且总是返回 true,即使它是错误的:
For some reason, my code isn't working and always returns true even if it's false:
def directory_exists?(directory)
return false if Dir[directory] == nil
true
end
我做错了什么?
推荐答案
如果您要查找的文件是否是 目录 而不仅仅是文件很重要,您可以使用 文件目录?
或 Dir.exist?一个>
.仅当文件存在并且是目录时才会返回 true.
If it matters whether the file you're looking for is a directory and not just a file, you could use File.directory?
or Dir.exist?
. This will return true only if the file exists and is a directory.
顺便说一句,编写方法的一种更惯用的方法是利用 Ruby 自动返回方法内最后一个表达式的结果这一事实.因此,你可以这样写:
As an aside, a more idiomatic way to write the method would be to take advantage of the fact that Ruby automatically returns the result of the last expression inside the method. Thus, you could write it like this:
def directory_exists?(directory)
File.directory?(directory)
end
请注意,在当前情况下不需要使用方法.
Note that using a method is not necessary in the present case.
这篇关于如何检查Ruby中是否存在给定目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!