How to add trailing slash if necessary using gsub

I am trying to add a trailing slash if necessary:

a = '/var/www'
a.gsub
...

I do not know how to do that.

+5
source share
9 answers
a = File.join(a, "")

Quickly, simply, and ensures that it aends in a path separator; that is, it gives the same result: a- "/var/www"or "/var/www/".

This is the same as Joe White's comment above; I do not know why he did not present it as an answer, since he deserves to be alone.

Oddly enough, the Pathname library does not provide a convenient way to do the same.

+21
source

Here's a slightly more readable version.

path << '/' unless path.end_with?('/')
+14
source

gsub?

  • ( )
  • , , sub not gsub.
  • , sub! gsub!.

, , :

path << '/' if path[-1] != '/' # Make sure path ends with a slash

: Ruby (1.8.x), :

path << '/' if path[-1].chr != '/' # Make sure path ends with a slash
+2

.. :

t = " "

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

47 -

0

script , :

a="/var/www";
print a + "\n";
a = a.gsub(/([^\/]$)/, '\1/');
print a + "\n";
a = a.gsub(/([^\/]$)/, '\1/');
print a + "\n";

:

/var/www
/var/www/
/var/www/

, ( /) /.

0

, , :

(a << '/').gsub!('//','/')

(a << '/').squeeze('/')

, "//" "/" , , , .

0
"/var/www".gsub(/[^\/]$/, '\1/')  #=> "/var/www/"
"/var/www/".gsub(/[^\/]$/, '\1/') #=> "/var/www/"
0

gsub, , (<)

a = '/var/www'
a.gsub('/?$', '/')

/ rep

0

You can use .chomp('/')to .concat('/')optionally terminate /and then .concat('/')to add a slash again.

'/var/www/'.chomp('/').concat('/')   # => "/var/www/"
'/var/www'.chomp('/').concat('/')    # => "/var/www/"
0
source

All Articles