how to get files count in a directory using ruby

Viewed 18885

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.

9 Answers

Using ~/Documents as example.

One line code:

Dir['~/Documents'].length

For longer paths one line can be less readable, so:

path = '~/Documents/foo/bar'

Dir[path].length

The current best answer does not count files in subdirectories starting with '.'. When we want to count files in subdirectories like '.git' or '.vs' then we need to use File::FNM_DOTMATCH argument but I am just beginner here not having 50 points so I can comment the best answer.

def folder_count(folder_path)
  Dir.glob("#{folder_path}/**/*", File::FNM_DOTMATCH).count { |file| File.file?(file) }
end

https://ruby-doc.org/core-2.5.0/Dir.html#method-c-5B-5D

"Note, this will not match Unix-like hidden files (dotfiles). In order to include those in the match results, you must use the File::FNM_DOTMATCH flag or something like "{,.}"."

Related