I'm trying to add trailing slash if needed:
a = '/var/www'
a.gsub
...
I don't know how to do it.
a = File.join(a, "")
Swift, simple, and has the effect of guaranteeing that a
ends in a path separator; that is, it gives the same result whether a
is "/var/www"
or "/var/www/"
.
This is same as Joe White's comment above; I don't know why he didn't submit it as an answer, as it deserves to be one.
Oddly, the Pathname library doesn't provide a convenient way of doing the same thing.
Here's a bit more readable version
path << '/' unless path.end_with?('/')
Why do you want to use gsub?
sub
not gsub
.sub!
or gsub!
.Since you're not doing substitution, just append the slash if needed:
path << '/' if path[-1] != '/' # Make sure path ends with a slash
Update: To make it compatible with older versions of Ruby (1.8.x), modify it slightly:
path << '/' if path[-1].chr != '/' # Make sure path ends with a slash
You can use .chomp('/')
to strip of the optionally trailing /
and then .concat('/')
to append a slash again.
'/var/www/'.chomp('/').concat('/') # => "/var/www/"
'/var/www'.chomp('/').concat('/') # => "/var/www/"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With