Check if directory is empty in Ruby

前端 未结 6 697
太阳男子
太阳男子 2020-12-14 15:57

How can I check to see if a directory is empty or not in Ruby? Is there something like:

Dir.exists?(\"directory\")

(I know that that functi

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 16:01

    An empty directory should only have two links (. and ..). On OSX this works:

    File.stat('directory').nlink == 2
    

    ...but does not work on Linux or Cygwin. (Thanks @DamianNowak) Adapting Pan's answer:

    Dir.entries('directory').size == 2
    

    should work.

提交回复
热议问题