有没有更简洁的内置方法来做到这一点?
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"]
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
Pathname.glob("/path/to/*/").map { |i| i.basename.to_s }