how to get files count in a directory using ruby how to get files count in a directory using ruby ruby ruby

how to get files count in a directory using ruby


The fastest way should be (not including directories in count):

Dir.glob(File.join(your_directory_as_variable_or_string, '**', '*')).select { |file| File.file?(file) }.count

And shorter:

dir = '~/Documents'Dir[File.join(dir, '**', '*')].count { |file| File.file?(file) }


All you need is this, run in the current directory.

Dir["**/*"].length

It counts directories as files.


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['**/*'] }