194

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?

5 Answers 5

331

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.

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Why bother even putting it inside another method? Just call it directly!
@Radar I figured that the stripped-down method was likely simplified for the purpose of the question and that the actual method might contain some additional logic. If no other logic needs to go in the method, I agree. By all means, just run directory? directly.
Wouldn't Dir.exists? not be cleaner than File.directory??
Dir.exists? is deprecated, use Dir.exist
@burningpony my bad, it's Dir.exist?
55

You can also use Dir::exist? like so:

Dir.exist?('Directory Name')

Returns true if the 'Directory Name' is a directory, false otherwise.1

Comments

48

All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:

File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true

Comments

19
File.exist?("directory")

Dir[] returns an array, so it will never be nil. If you want to do it your way, you could do

Dir["directory"].empty?

which will return true if it wasn't found.

Comments

7

You could use Kernel#test:

test ?d, 'some directory'

it gets it's origins from https://ss64.com/bash/test.html you will notice bash test has this flag -d to test if a directory exists -d file True if file is a Directory. [[ -d demofile ]]

1 Comment

This is neat. Not the most immediately expressive, but neat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.