tags:

views:

91

answers:

1

In ruby, I'm able to do

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

and get

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

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

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

Is there a way to do that other than using

directory_string.split("/")[1:-1]
+7  A: 

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)

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]
Rudd Zwolinski
Note that on Windows File::SEPERATOR is /, not \. So if you only use that method on the result of File.join, it will work fine, but if you want to work with user input or other sources that could use \ as a file seperator you should do something like `dir.split(Regexp.union(*[File::SEPARATOR, File::ALT_SEPARATOR].compact))` (or a more readable version of that)
sepp2k