我想将路径的单个组件作为数组. 我来到这两个解决方案: path = '/usr/share/doc/less/'parts = path.split(File::Separator)p parts # = ["", "usr", "share", "doc", "less"]require 'pathname'parts = []Pathname.new(path).each
我来到这两个解决方案:
path = '/usr/share/doc/less/' parts = path.split(File::Separator) p parts # => ["", "usr", "share", "doc", "less"] require 'pathname' parts = [] Pathname.new(path).each_filename {|f| parts << f} p parts # => ["usr", "share", "doc", "less"]
> String.split()
这种坚固且便携吗?
> Pathname.each_filename()
Ruby看起来有点冗长.但是,这应该是便携式的,对吗?
还有更好的方法吗?我错过了标准Ruby的东西吗?
那就是现场. Pathname是ruby标准库的一部分,它应该是一个完全可移植的解决方案.你可以使用这个:
Pathname.new(path).each_filename.to_a
甚至:
Pathname(path).each_filename.to_a