method
join
ruby latest stable - Class:
File
join(*args)public
Returns a new string formed by joining the strings using "/".
File .join ("usr", "mail", "gumby") #=> "usr/mail/gumby"
static VALUE
rb_file_s_join(VALUE klass, VALUE args)
{
return rb_file_join(args);
} 2Notes
Works with URLs too!
railsmonk · Oct 9, 20086 thanksYou 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.
Eliminates Double Slashes
iq-9 · Feb 10, 2011Also eliminates inadvertent double slashes:
path = '/uploads/art/'
file = '/pic.jpg'
File.join(path, file) # => '/uploads/art/pic.jpg'