2

我想我已经接近了,但正则表达式没有评估。希望有人知道原因。

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

当我传入小写标题时,它们会以小写形式返回。

4

3 回答 3

3

您需要正确锚定正则表达式:

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

这是因为/a/匹配一个带有 an 的单词a/\Aa\Z/匹配一个完全由 , 组成的字符串a,并/\A(a|of|...)\Z/匹配一组单词。

无论如何,您可能想要的是:

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

在这里使用正则表达式有点笨拙。你想要的是一个排除列表。

于 2013-04-04T14:36:47.123 回答
1

这被称为 titleize,并且是这样实现的:

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

查看文档。

如果你想要花哨的titlezing,请查看granth's titleize

于 2013-04-04T14:44:37.033 回答
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
于 2013-04-04T14:43:05.897 回答