在 ruby​​ 中以内置方式列出目录中的目录

发布于 2024-08-16 12:41:14 字数 215 浏览 2 评论 0原文

有没有更干净的内置方法来做到这一点?

ree> Pathname.new('/path/to').children.select{|e| e.directory?}.map{|d| d.basename.to_s}
 => ["test1", "test2"]

理想情况下,我想避免 directory? 调用

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时常饿 2024-08-23 12:41:14

从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

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
可是我不能没有你 2024-08-23 12:41:14
Pathname.glob("/path/to/*/").map { |i| i.basename.to_s }
Pathname.glob("/path/to/*/").map { |i| i.basename.to_s }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文