Re: how to calculate file number in a folder

From: Li Chen

but I am not sure how to calculate the number of file in folder.
Any help will be appreciated.

Here’s one way. (There are many, I’m sure.)

#Find all the entries in a directory
irb(main):009:0> Dir[ ‘c:/ruby/*’ ]
=> [“c:/ruby/bin”, “c:/ruby/ChangeLog.txt”, “c:/ruby/doc”,
“c:/ruby/freeride”, “c:/ruby/lib”, “c:/ruby/LICENSE.txt”, “c:/ruby/man”,
“c:/ruby/MANIFEST”, “c:/ruby/README.1st”, “c:/ruby/ReleaseNotes.txt”,
“c:/ruby/ruby.ico”, “c:/ruby/rubyw.ico”, “c:/ruby/samples”,
“c:/ruby/scite”, “c:/ruby/share”, “c:/ruby/src”,
“c:/ruby/uninstall.exe”]

Find select just the ones that are files:

irb(main):010:0> Dir[ ‘c:/ruby/*’ ].select{ |path| File.file?( path ) }
=> [“c:/ruby/ChangeLog.txt”, “c:/ruby/LICENSE.txt”, “c:/ruby/MANIFEST”,
“c:/ruby/README.1st”, “c:/ruby/ReleaseNotes.txt”, “c:/ruby/ruby.ico”,
“c:/ruby/rubyw.ico”, “c:/ruby/uninstall.exe”]

Find the length of that list

irb(main):011:0> Dir[ ‘c:/ruby/*’ ].select{ |path| File.file?( path )
}.length
=> 8

One other way:

file_count = 0
Dir[ ‘c:/ruby/*’ ].each{ |path|
if File.file?( path )
# Do something to the file
file_count += 1
end
}

Here’s one way. (There are many, I’m sure.)

#Find all the entries in a directory
irb(main):009:0> Dir[ ‘c:/ruby/*’ ]

Find select just the ones that are files:

irb(main):010:0> Dir[ ‘c:/ruby/*’ ].select{ |path| File.file?( path ) }

Find the length of that list

irb(main):011:0> Dir[ ‘c:/ruby/*’ ].select{ |path| File.file?( path )
}.length
=> 8

One other way:

file_count = 0
Dir[ ‘c:/ruby/*’ ].each{ |path|
if File.file?( path )
# Do something to the file
file_count += 1
end
}

Thank you,

Li