# In the current working dir:
#
Dir.entries( '.' ).select{ |f| File.file? f }
# In another directory, relative or otherwise, you need to transform the path
# so it is either absolute, or relative to the current working dir to call File.xxx functions:
#
home = "/home/test"
Dir.entries( home ).select{ |f| File.file? File.join( home, f ) }
To get all files (strictly files only) recursively:
Dir.glob('path/**/*').select { |e| File.file? e }
Or anything that's not a directory (File.file? would reject non-regular files):
Dir.glob('path/**/*').reject { |e| File.directory? e }
Alternative Solution
Using Find#find over a pattern-based lookup method like Dir.glob is actually better. See this answer to "One-liner to Recursively List Directories in Ruby?".
20条答案
按热度按时间wmtdaxz316#
在Ruby 2.5中,您现在可以使用
Dir.children
。它以数组的形式获取文件名,但“.”除外。和“..”示例:
Http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children
hts6caw317#
这对我很管用:
如果您不想要隐藏文件[1],请使用Dir[]:
现在,目录条目将返回隐藏文件,并且您不需要通配符Asterix(您可以只传递带有目录名的变量),但它将直接返回基本名称,因此File.xxx函数将不起作用。
[1]
.dotfile
在Unix上,我不知道Windowsuajslkp618#
To get all files (strictly files only) recursively:
Or anything that's not a directory (
File.file?
would reject non-regular files):Alternative Solution
Using
Find#find
over a pattern-based lookup method likeDir.glob
is actually better. See this answer to "One-liner to Recursively List Directories in Ruby?".lrl1mhuk19#
以下代码片断准确地显示了目录中文件的名称,跳过了子目录和
"."
、".."
点分文件夹:xxhby3vn20#
示例:
消息来源:http://ruby-doc.org/core/classes/Dir.html#method-c-entries