how to get files count in a directory using ruby

2020-05-20 07:14发布

using ruby how to get number of files in a given Directory,the file count should include count from recursive directories.

Eg: folder1(2 files) -----> folder2(4 files) and folder2 is inside folder1. total count for above case should be 6 files.

is there any function in ruby which fetch me this count.

8条回答
放我归山
2楼-- · 2020-05-20 08:14

You could also go super bare bones and do a system command:

count = `ls -1 #{dir} | wc -l`.to_i 
查看更多
不美不萌又怎样
3楼-- · 2020-05-20 08:20

A slight modification and a comment

Dir['**/*'].count { |file| File.file?(file) }

works for me in Ruby 1.9.3, and is shorter.

A caveat, at least on my Windows 7 box, is that Dir['somedir/**/*'] doesn't work. I have to use

cd(somedir) { Dir['**/*'] }
查看更多
登录 后发表回答