Ash Ash - 7 months ago 50
Ruby Question

How to check if a given directory exists in Ruby

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.

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


What am I doing wrong?

Answer

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.exists?. This will return true only if the file exists and is a directory.

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