Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add trailing slash if needed with gsub

Tags:

ruby

gsub

I'm trying to add trailing slash if needed:

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

I don't know how to do it.

like image 843
gsub Avatar asked Aug 13 '10 12:08

gsub


4 Answers

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.

like image 108
matt Avatar answered Nov 04 '22 12:11

matt


Here's a bit more readable version

path << '/' unless path.end_with?('/')
like image 38
Ruslan Ulanov Avatar answered Nov 04 '22 11:11

Ruslan Ulanov


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
like image 22
Lars Haugseth Avatar answered Nov 04 '22 13:11

Lars Haugseth


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/"
like image 41
To1ne Avatar answered Nov 04 '22 12:11

To1ne