2013-04-04 44 views
2

我認爲我很接近,但是正則表達式沒有評估。希望有人知道爲什麼。在if,else語句中測試正則表達式

def new_title(title) 
    words = title.split(' ') 
    words = [words[0].capitalize] + words[1..-1].map do |w| 
    if w =~ /and|an|a|the|in|if|of/ 
     w 
    else 
     w.capitalize 
    end 
    end 
    words.join(' ') 
end 

當我傳遞小寫字母時,它們會以小寫形式返回。

回答

3

您需要正確錨正則表達式:

new_title("the last hope") 
# => "The last Hope" 

這是因爲/a/一個字相匹配,在它的a/\Aa\Z/匹配完全由a/\A(a|of|...)\Z/組成的字符串,並與一組單詞匹配。

在任何情況下,你可能想是這樣的:

case (w) 
when 'and', 'an', 'a', 'the', 'in', 'if', 'of' 
    w 
else 
    w.capitalize 
end 

這裏使用正則表達式是有點重手。你想要的是一個排除列表。

0

您的正則表達式應該是檢查整個單詞(^word$)。無論如何,是不是更簡單易用Enumerable#include?

def new_title(title) 
    words = title.split(' ') 
    rest_words = words.drop(1).map do |word| 
    %w(and an a the in if of).include?(word) ? word : word.capitalize 
    end 
    ([words[0].capitalize] + rest_words).join(" ") 
end 
+0

是的,包括肯定是我通常做的,但我正在做一些正則表達式的練習。 – bwobst 2013-04-04 14:45:44

1

這就是所謂的titleize,而像這樣實現的:

def titleize(word) 
    humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize } 
end 

Se the doc.

如果你想看中titlezing,退房granth's titleize