I'm trying to add trailing slash if needed:
a = "/var/www"
a.gsub... I dont know how to do it.
I'm trying to add trailing slash if needed:
a = "/var/www"
a.gsub... I dont know how to do it.
This is not very nice looking.. but works:
t = "some text"
t[-1] == 47 ? t : t + "/"
47 is a backslash code
The following script shows how this can be done:
a="/var/www";
print a + "\n";
a = a.gsub(/([^\/]$)/, '\1/');
print a + "\n";
a = a.gsub(/([^\/]$)/, '\1/');
print a + "\n";
It outputs:
/var/www
/var/www/
/var/www/
and works by substituting the last character of the line (if it's not a /
) with the same character plus a trailing /
as well.
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
There are a couple of different ways that have already been covered, to through another into the mix:
(a << '/').gsub!('//','/')
or
(a << '/').squeeze('/')
It's worth noting though that both of those will convert any cases of '//' to '/' anywhere in the string, though if you are just dealing with paths, that's unlikely to cause problems.
"/var/www".gsub(/[^\/]$/, '\1/') #=> "/var/www/"
"/var/www/".gsub(/[^\/]$/, '\1/') #=> "/var/www/"