RUBY |找到一种方法在相同的单词上找到一个异常要大写


def titleize(string)
nocaps = ["the","and"]
puts string.split(" ").map { |word| nocaps.include?(word) ? word : word.capitalize }.join(" ")
end
titleize("the bridge over the river kwai")
------------------------------------------------------------------------------------------
######Render => "the Bridge Over the River Kwai"
######Expected rendering => "The Bridge Over the River Kwai"

你好,我给你我的一段代码,渲染给出"桂河大桥"虽然我想"桂河大桥";因此,我想找到一种方法,在同一个单词上找到一个例外。

您的代码,但始终大写第一个字母,使用each_with_index获得数组中的位置:

def titleize(string)
nocaps = ["the","and"]
string.split(" ").each_with_index.map { |word, i| i.positive? && nocaps.include?(word) ? word : word.capitalize }.join(" ")
end
titleize("the bridge over the river kwai")

字符串首字母大写

有很多方法可以做到这一点,但其中一种方法是在决定是否将单个单词大写之前将整个String对象大写。例如:
def titleize str 
stopwords   = %w[the and]
title_words = str.capitalize.split.map! do |word| 
stopwords.include?(word) ? word : word.capitalize
end.join ?s
end
p titleize("the bridge over the river kwai")
#=> "The Bridge Over the River Kwai"
p titleize("the bridge over the river kwai and the amazon")
#=> "The Bridge Over the River Kwai and the Amazon"

在底层,这实际上会将除第一个字母以外的所有单词都小写,然后编程地将不在stopwords中的每个单词大写。因此,它依赖于一些隐式行为,但对于发布的示例来说效果很好。

一种方法如下:

def titleize(str, little_words)
str.downcase.split.map.with_index do |word,i|
little_words.include?(word) && i > 0 ? word : word.capitalize
end.join(" ")
end
str = "the briDge over   The river kwai"    
titleize(str, ["the", "and"])
#=> "The Bridge Over the River Kwai"

下面是直接对字符串进行操作的第二种方法(不是将其转换为数组或单词,而是对这些单词进行替换,然后将结果数组连接起来):

def titleize(str, little_words)
str.downcase.gsub(/(?<= )p{L}+/) do |s|
little_words.include?(s) ? s : s.capitalize
end
end
titleize(str, ["the", "and"])
#=> "The Bridge Over   the River Kwai"

注意此方法保留str中单词之间的额外空格。

正则表达式为,&;匹配一个或多个Unicode字母(p{L}+)(贪婪地),前面加一个空格&;

此操作的一种变体是将非little_words中的所有单词大写,然后将结果字符串的第一个字符大写:

def titleize(str, little_words)
str.downcase.gsub(/p{L}+/) do |s|
little_words.include?(s) ? s : s.capitalize
end.tap { |s| s[0] = s[0].upcase }
end

看到对象#水龙头。

如果little_words包含很多单词,方法可以先将该数组转换为little_words_set(require 'set'; little_words_set = little_words.to_set),然后在little_words出现的地方替换little_words_set

这可以通过从@Todd的回答中得到改进:用capitalize替换downcase,避免需要tap子句。

请注意,little words是出版界使用的术语。

虽然其他答案都是你原来的帖子,但我想我会提供另一种选择,使用正则表达式。

def titleize(str) 
nocaps = ["the","and"]
str.gsub(/A.|b(!?#{Regexp.union(nocaps)})bw+/,&:capitalize) 
end 
titleize("the bridge over the river and through the woods kwai")
#=> "The Bridge Over the River and Through the Woods Kwai"

这个正则表达式将选择第一个字母A.nocapsArray中不包含的任何其他单词,然后它将用大写版本替换每个选中的单词。

本例中生成的正则表达式为/A.|b(?!(?-mix:the|and))bw+/

相关内容

最新更新