是否有更简洁的内置方法来执行此操作?
ree> Pathname.new('/path/to').children.select{|e| e.directory?}.map{|d| d.basename.to_s}
=> ["test1", "test2"]
理想情况下,我想避免 directory?
调用
最佳答案
从Chandra的回答开始,看你是否需要完整路径,你可以使用
Dir['app/*/']
# => ["app/controllers/", "app/helpers/", "app/metal/", "app/models/", "app/sweepers/", "app/views/"
Dir['app/*/'].map { |a| File.basename(a) }
# => ["controllers", "helpers", "metal", "models", "sweepers", "views"]
如果你使用Ruby >= 1.8.7,Chandra的答案也可以重写为
Pathname.glob('app/*/').map(&:basename)
# you can skip .to_s unless you don't need to work with strings
# remember you can always use a pathname as string for the most part of Ruby functions
# or interpolate the value
关于ruby - 内置在 ruby 目录中列出目录的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2011234/