2013-02-10 32 views
0

我有這樣的:如果正則表達式不匹配,Ruby如何輕鬆分配固定值?

author = m.match(/Author: (\w*)/)[1].strip 

它有時會扔我一個「未定義的方法[]」例外

什麼是分配一個固定值的最佳方法(例如「」或「未找到」)如果正則表達式不匹配?也許是救援?

+1

'strip'調用是多餘的,因爲'\ w *'不會捕獲任何'strip'會刪除的東西。 – 2013-02-10 16:34:45

回答

3

做到這一點的最好辦法是:

author = m[/regex/, 1] || "not found" 

紅寶石,實在令人匪夷所思。

+0

謝謝阿諾德;沒有一天,沒有我學習紅寶石真棒和新鮮的smth。 – mudasobwa 2013-02-10 16:56:39

3
def find_author s 
    s =~ /Author: (\w*)/ ? $1 : 'not found' 
end 

find_author 'Author: Joe' # => "Joe" 
find_author 'No author here' # => "not found" 
+0

怎麼稱爲=〜操作符? – 2013-02-10 16:35:11

+0

嗯,我不知道。我稱之爲「正則匹配運算符」? :) – 2013-02-10 16:35:47

+0

@ArnoldRoa我相信鎬會將它稱爲「模式匹配運算符」,以及'!〜'。 – 2013-02-10 16:37:33