如何检查给定目录在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
返回false
我在做什么错了?
What am I doing wrong?
推荐答案
如果要查找的文件是否为目录,而不仅仅是文件,您可以使用 文件目录?
或 Dir.exist?
。
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屋!