Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make sure a string starts or ends with another string in Rails

Is there an easy way to apply the following logic to a string in Rails?

if string does NOT end with '.' then add '.'
if string does NOT begin with 'http://' then add 'http://'.

Of course, one might do something like:

string[0..6] == 'http://' ? nil : (string = 'http://' + string)

But it is a little clunky and it would miss the https:// alternative. Is there a nicer Rails way to do this?

like image 236
sscirrus Avatar asked Sep 17 '11 02:09

sscirrus


3 Answers

Regex's are key, but for a simple static string match, you could use helper functions which are faster. Also, you could use << instead of + which is also faster (though probably not a concern).

string << '.' unless string.end_with?( '.' )
string =  'http://' << string unless string.start_with?( 'http://' )

note, s will contain the correct value, but the return value is nil if the string was not changed. not that you would, but best not to include in a conditional.

like image 167
pduey Avatar answered Nov 15 '22 04:11

pduey


Something like

string = "#{string}." unless string.match(/\.$/)
string = "http://#{string}" unless string.match(/^https?:\/\//)

should work.

like image 42
Michael Irwin Avatar answered Nov 15 '22 04:11

Michael Irwin


These will work in 1.9:

s += '.' unless s[-1] == '.'
s  = 'http://' + s unless s[/^https?:\/\//]

The first one won't work in 1.8 though.

like image 28
mu is too short Avatar answered Nov 15 '22 06:11

mu is too short