Check if Folder Exists in Ruby (Case-Sensitive)

Ruby’s Dir.exist? is tied to your OS, which may or may not be case sensitive when it comes to directories. That means that it is possible for a directory named ‘Derp’ to exist, but Dir.exist?(‘derp’) would return true.

Here’s a convoluted piece of code to get past that. It adds another method to the Dir class (since this is Ruby, we can’t overload methods)

class Dir
  def self.exist_with_case?(dir)

p Dir.exist_with_case?('derp')
p Dir.exist_with_case?('Derp')

This codedoesn’t specifically check to see if it is checking against directories or files, but whatevs.

I have a situation where a Vagrant box that uses Guest Additions has weird behavior after copying files from Windows. Any attempts to rename the folders from within Vagrant results in errors about the folders being busy. Deleting the files is no problem.
We are copying folders with lowercase names to Vagrant, and then need to change them to have an uppercase letter.
This is all for a refactoring project in PHP. I love Ruby, so I am writing scripts in Ruby to avoid using PHP. It’s working out rather well so far.

Leave a Reply

Your email address will not be published. Required fields are marked *