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?
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.
Something like
string = "#{string}." unless string.match(/\.$/)
string = "http://#{string}" unless string.match(/^https?:\/\//)
should work.
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.
精彩评论