内置方式列出ruby目录中的目录 [英] Built in way to list directories in a directory in ruby
本文介绍了内置方式列出ruby目录中的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ree> Pathname.new( /路径/到)children.select {|即| e.directory} {地图|?开发| d.basename.to_s}
=> [test1,test2]
理想情况下,我想避免目录?
调用
解决方案
从Chandra的答案开始,取决于是否需要完整路径,您可以使用
目录['app / * /']
#=> [app / controllers /,app / helpers /,app / metal /,app / models /,app / sweepers /,app / views /
Dir ['app / * /']。map {| a | File.basename(a)}
#=> [控制器,助手,金属,模特儿,扫除者,意见]
如果您使用Ruby> = 1.8.7,Chandra的答案也可以重写为
Pathname.glob(' app / * /')。map(&:basename)
#你可以跳过.to_s,除非你不需要使用字符串
#记住你可以随时使用路径名作为字符串大部分Ruby函数
#或内插值
Is there a cleaner built-in way to do this?
ree> Pathname.new('/path/to').children.select{|e| e.directory?}.map{|d| d.basename.to_s}
=> ["test1", "test2"]
Ideally I would like to avoid the directory?
call
解决方案
Starting from Chandra's answer, depending on whether you need or not the full path, you can use
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"]
If you use Ruby >= 1.8.7, Chandra's answer can also be rewritten as
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目录中的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文