ruby - 内置在 ruby​​ 目录中列出目录的方法

标签 ruby file directory

是否有更简洁的内置方法来执行此操作?

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/

相关文章:

c# - 在没有安装 Sharepoint 的情况下在 VS 2010 中创建 Sharepoint 目录

ruby - 从 Watir/Ruby 中的 webtable 中提取文本

ruby - 使用Ruby解压缩3字节/24位数据 block

ruby - Chef : how to get a timestamp at *convergence* rather than *compile* time

python - 如何在Python中使用glob模式读取目录中的文件?

Unix 软链接(soft link)和路径

ruby-on-rails - Rails 4 父类(super class)在生产中仅与管理命名空间不匹配

php - 将多个文本文件上传到 MySQL

java - 更改JComboBox的标签

linux - 页面上显示大量文件的最佳目录结构