tags:

views:

916

answers:

2

I am trying to write a script which automatically checks out or updates a subverion url based on whether a specified directory exists or not, but from some reason, my code isnt working and always returns 'true' even if its false.

The code:

def directory_exists?(directory)
  return false if Dir[directory] == nil
  true
end

Can someone help me? What am I doing wrong?

+5  A: 

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.

cloudhead
+11  A: 

If it matters whether the file you're looking for is a directory and not just a file, you could use File.directory?("name"). 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
Emily
Just a link to the doco:http://www.ruby-doc.org/core/classes/File.html#M002555
Nippysaurus
Why bother even putting it inside another method? Just call it directly!
Ryan Bigg
@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.
Emily