tags:

views:

44

answers:

5

I'm trying to add trailing slash if needed:

a = "/var/www"

a.gsub... I dont know how to do it.

A: 

This is not very nice looking.. but works:

t = "some text"

t[-1] == 47 ? t : t + "/"

47 is a backslash code

Marek Kowalski
You want to use `?/` which will give you either the character code (on Ruby 1.8) or a 1-character string (on Ruby 1.9) and will always be compatible with `t[-1]`
Ken Bloom
A: 

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.

paxdiablo
+1  A: 

Why do you want to use gsub?

  1. You're not doing substitution (nothing is to be removed from the string)
  2. If you're substituting, and only need it done in one place, use sub not gsub.
  3. If you're substituting, and want to modify the string, use 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
Lars Haugseth
That wont work as a[-1] will return the character code, not the character, you want something more like: a << '/' if a[-1].chr != '/'
darkliquid
@darkliquid: It works in Ruby 1.9. Updated my answer, thanks.
Lars Haugseth
Another route to 1.8 compatibility is path << '/' unless path[-1..-1] == '/'.
glenn mcdonald
A: 

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.

darkliquid
+1  A: 
"/var/www".gsub(/[^\/]$/, '\1/')  #=> "/var/www/"
"/var/www/".gsub(/[^\/]$/, '\1/') #=> "/var/www/"
Konsi