Empty directory

From Rosetta Code
Revision as of 15:45, 2 January 2012 by rosettacode>Kernigh (This Ruby code is ugly, but seems to work.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Empty directory is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Starting with a path to some directory, determine whether the directory is empty.

An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains entries for '.' and '..'; an empty directory contains no other entries.

Ruby

Works with: Ruby version 1.8.7

<lang ruby># Checks if a directory is empty, but raises SystemCallError

  1. if _path_ is not a directory.

def empty_dir?(path)

 not Dir.foreach(path).detect {|f| f != '.' and f != '..'}

end</lang>

If Ruby is older than 1.8.7, then Dir.foreach must take a block.

<lang ruby># Checks if a directory is empty, but raises SystemCallError

  1. if _path_ is not a directory.

def empty_dir?(path)

 Dir.foreach(path) {|f|
   return false if f != '.' and f != '..'
 }
 return true

end</lang>