Ruby 在If,Else语句中测试正则表达式

Ruby 在If,Else语句中测试正则表达式,ruby,regex,Ruby,Regex,我想我很接近了,但正则表达式没有评估。希望有人知道原因 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 当我传入小写标

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

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

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

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

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

在这里使用正则表达式有点麻烦。您需要的是一个排除列表。

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

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

在这里使用正则表达式有点麻烦。您需要的是一个排除列表。

您的正则表达式应该检查整个单词(
^word$
)。总之,使用
可枚举#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

正则表达式应该检查整个单词(
^word$
)。总之,使用
可枚举#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

这称为titleize,实现方式如下:

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


如果您想要奇特的标题化,请查看

这称为标题化,其实现方式如下:

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


如果你想要有趣的标题,请查看

是的,include肯定是我通常会做的,但我对正则表达式做了一些练习。是的,include肯定是我通常会做的,但我对正则表达式做了一些练习。