Errno::ENOTDIR
RubyERRORNotableFilesystem
Path component is not a directory
Quick Answer
Check File.directory? on path components before performing directory operations.
What this means
Raised when a directory operation is performed on a path component that exists but is a regular file rather than a directory. Maps to POSIX errno 20.
Why it happens
- 1Using a file path where a directory is expected (e.g., Dir.entries on a file)
- 2A path component in a long path points to a file instead of a directory
Fix
Validate path type before use
Validate path type before use
def ensure_dir(path)
raise Errno::ENOTDIR, "#{path} is not a directory" unless File.directory?(path)
path
endWhy this works
File.directory? returns true only if the path exists and is a directory.
Code examples
Reproducing the errorruby
File.write('myfile', 'data')
Dir.entries('myfile')
# Errno::ENOTDIR: Not a directory - myfileCheck before useruby
File.directory?(path) ? Dir.entries(path) : raise("Not a directory: #{path}")Rescue ENOTDIRruby
begin
Dir.foreach(candidate) { |f| puts f }
rescue Errno::ENOTDIR
puts "#{candidate} is a file, not a directory"
endSame error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev