如何在Ruby中拆分目录字符串?

时间:2009-09-03 01:14:50

标签: ruby linux windows string

在红宝石中,我能够做到

File.dirname("/home/gumby/bigproject/now_with_bugs_fixed/32/FOO_BAR_2096.results")

并获取

"/home/gumby/bigproject/now_with_bugs_fixed/32"

但现在我想将该目录字符串拆分为单个文件夹组件,例如

["home", "gumby", "bigproject", "now_with_bugs_fixed", "32"]

除了使用

之外,还有其他办法吗?
directory.split("/")[1:-1]

5 个答案:

答案 0 :(得分:36)

正确的答案是使用Ruby的Pathname(1.8.7以内的内置类,而不是gem)。

参见代码:

require 'pathname'

def split_path(path)
    Pathname(path).each_filename.to_a
end

执行此操作将丢弃路径是绝对路径还是相对路径的信息。要检测到这种情况,您可以在absolute?上调用Pathname方法。

来源:https://ruby-doc.org/stdlib-2.3.3/libdoc/pathname/rdoc/Pathname.html

答案 1 :(得分:24)

没有内置函数可以将路径拆分到其组件目录中,就像要加入它们一样,但是您可以尝试以跨平台的方式伪造它:

directory_string.split(File::SEPARATOR)

这适用于相对路径和非Unix平台,但对于以"/"作为根目录开头的路径,那么你将得到一个空字符串作为数组中的第一个元素,我们我想改为"/"

directory_string.split(File::SEPARATOR).map {|x| x=="" ? File::SEPARATOR : x}

如果您只想要如上所述的没有根目录的目录,那么您可以将其更改为从第一个元素中选择。

directory_string.split(File::SEPARATOR).map {|x| x=="" ? File::SEPARATOR : x}[1..-1]

答案 2 :(得分:7)

Rake提供了一个添加到FileUtils的split_all方法。它非常简单,使用File.split:

def split_all(path)
  head, tail = File.split(path)
  return [tail] if head == '.' || tail == '/'
  return [head, tail] if head == '/'
  return split_all(head) + [tail]
end

taken from rake-0.9.2/lib/rake/file_utils.rb

rake版本与Rudd代码的输出略有不同。 Rake的版本忽略了多个斜杠:

irb(main):014:0> directory_string = "/foo/bar///../fn"
=> "/foo/bar///../fn"
irb(main):015:0> directory_string.split(File::SEPARATOR).map {|x| x=="" ? File::SEPARATOR : x}[1..-1]
=> ["foo", "bar", "/", "/", "..", "fn"]
irb(main):016:0> split_all directory_string
=> ["/", "foo", "bar", "..", "fn"]
irb(main):017:0>

答案 3 :(得分:2)

警告:此解决方案不再是最佳解决方案。看到我的另一个。

实际上,有一个更简洁的解决方案。主要想法是保持弹出基本名称,直到您只剩下./

def split_path(path)
    array = []
    until ['/', '.'].include? path
        array << File.basename(path)
        path = File.dirname(path)
    end
    array.reverse
end

split_path 'a/b/c/d' #=> ['a', 'b', 'c', 'd']

如果你愿意,你可以进一步发展这个想法。

答案 4 :(得分:0)

你想要:

File.split( "/home/gumby/bigproject/now_with_bugs_fixed/32/FOO_BAR_2096.results").first
=> "/home/gumby/bigproject/now_with_bugs_fixed/32"