split(p1) public

Splits the given string into a directory and a file component and returns them in a two-element array. See also File::dirname and File::basename.

File.split("/home/gumby/.profile")   #=> ["/home/gumby", ".profile"]
Show source
Register or log in to add new notes.
October 9, 2008
1 thank

Works for URLs too

You can use it for web urls as well:

path, file = File.split('/uploads/art/2869-speaking-of-pic.jpg')
p path # => "/uploads/art"
p file # => "2869-speaking-of-pic.jpg"

And you can also use join, to merge url back from the components:

path = File.join(["/uploads/art", "2869-speaking-of-pic.jpg"])
p path # => "/uploads/art/2869-speaking-of-pic.jpg"

Using #join and #split for operations on files and path parts of the URLs is generally better than simply joining/splitting strings by ‘/’ symbol. Mostly because of normalization:

File.split('//tmp///someimage.jpg') # => ["/tmp", "someimage.jpg"]
'//tmp///someimage.jpg'.split('/') # => ["", "", "tmp", "", "", "someimage.jpg"]

Same thing happens with join.