[英]Ruby - Get all files in a directory from shallower to deeper
Dir
的魔力,我可以将所有文件保存在目录中:
Dir['lib/**/*.rb']
=> ["lib/a.rb", "lib/foo/bar/c.rb", "lib/foo/b.rb"]
但我想将它们从浅到深进行迭代。 即a.rb
> b.rb
> c.rb
有什么建议吗?
好吧,您可以按斜杠的数量对它们进行排序,这可能不是很有效,但很容易:
["lib/a.rb", "lib/foo/bar/c.rb", "lib/foo/b.rb"].sort_by { |s| s.count('/') }
#=> ["lib/a.rb", "lib/foo/b.rb", "lib/foo/bar/c.rb"]
或使用group_by
并在每个目录级别获取文件数组:
["lib/a.rb", "lib/foo/bar/c.rb", "lib/foo/b.rb"].group_by { |s| s.count('/') }
#=> {1=>["lib/a.rb"], 3=>["lib/foo/bar/c.rb"], 2=>["lib/foo/b.rb"]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.