2011-09-17 8 views
3

次のロジックをRailsの文字列に適用する簡単な方法はありますか?もちろんRailsで文字列の開始または終了を確認する

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

、1のような何かするかもしれない:

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

をしかし、それは少し不格好であり、それはhttps://代替を欠場だろう。これを行うためのより良いRailsの方法はありますか?

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

のようなものが動作するはず

答えて

6

3

これらは1.9で動作します:

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

最初のものはしかし1.8では動作しません。

12

正規表現はキーですが、単純な静的文字列一致の場合、より高速なヘルパー関数を使用できます。また、+の代わりに< <を使用することもできますが、これは高速です(おそらく問題はありません)。

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

メモ:sには正しい値が含まれますが、文字列が変更されていない場合は戻り値はnilです。あなたはそうではありませんが、条件付きで含めるのは最善ではありません。

関連する問題