如何在Ruby中拆分目录字符串? [英] How to split a directory string in Ruby?

查看:46
本文介绍了如何在Ruby中拆分目录字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在红宝石中,我能够做到

In ruby, I'm able to do

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

并获得

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

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

but now I'd like to split up that directory string into the individual folder components, ie something like

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

除了使用

directory.split("/")[1:-1]

推荐答案

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

There's no built-in function to split a path into its component directories like there is to join them, but you can try to fake it in a cross-platform way:

directory_string.split(File::SEPARATOR)

这适用于相对路径以及在非Unix平台上,但是对于以"/" 开头的路径作为根目录,那么您将获得一个空字符串作为您的第一个元素数组,我们需要"/" .

This works with relative paths and on non-Unix platforms, but for a path that starts with "/" as the root directory, then you'll get an empty string as your first element in the array, and we'd want "/" instead.

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

如果您只想像上面提到的那样没有根目录的目录,则可以将其更改为从第一个元素开始进行选择.

If you want just the directories without the root directory like you mentioned above, then you can change it to select from the first element on.

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

这篇关于如何在Ruby中拆分目录字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆