我正在研究一种方法,将句子中每个单词的第一个字母大写,除非是其中一个小单词。 (无论如何,句子中的第一个单词总是大写)
我有以下内容:
def titleize(t)
little = ["over", "the", "and"]
q = t.split(" ")
u = []
q.each do |i|
p = i.split("")
p[0] = p[0].upcase
r = p.join("")
if i == q[0]
u.push(r)
elsif i == little[0] || i == little[1] || i == little[2]
u.push(i)
else
u.push(r)
end
end
s = u.join(" ")
return s
end
当我通过测试时,我得到:
Failure/Error: titleize("the bridge over the river kwai").should == "The Br
idge over the River Kwai"
expected: "The Bridge over the River Kwai"
got: "The Bridge over The River Kwai" (using ==)
为什么句子中的第二个“the”获得大写?
答案 0 :(得分:0)
编辑:这是我原始建议的另一个解决方案,代码为:
class String
def titleize(exclusions)
words = self.split.map do |word|
exclusions.include?(word) ? word : word.capitalize
end
words.first.capitalize!
words.join(" ")
end
end
string = "the bridge over the river kwai"
exclusions = %w{ over the and }
p string.titleize(exclusions)
#=> "The Bridge over the River Kwai"
原始答案: 如何只是将整个字符串中的每个单词大写,然后使用gsub在适当的时候用低级版本替换这些单词?
string = "the bridge over the river kwai"
exclusions = %w{ over the and }
p string.split.map(&:capitalize).join(" ").gsub(/(?<!^)(#{exclusions.join("|")})/i) {|word| word.downcase}
#=> "The Bridge over the River Kwai"
答案 1 :(得分:0)
由于q[0]
是"the"
,所以当i
为"the"
时,它满足条件:
i == q[0]
更好的方法是:
Little = %w[over the and]
def titleize s
s.gsub(/\w+/)
.with_index{|w, i| i.zero? || Little.include?(w).! ? w.capitalize : w}
end
titleize("the bridge over the river kwai")
# => "The Bridge over the River Kwai"
答案 2 :(得分:0)
上述变体:
def titleize(s)
s.sub( /\w+/) { |w| w.capitalize }
.gsub(/\w+/) { |w| Little.include?(w) ? w : w.capitalize }
end
试一试:
s =<<THE_END
to protect his new shoes from the rain, a man stood atop a stack of
newspapers in Times Square. When the newsstand's proprietor asked
if he realized what he was standing on, he replied, "of course,
these are the times that dry men's soles".
THE_END
Little = ["the", "and", "a", "on", "to", "from", "in"]
titleize(s)
#=> "To Protect His New Shoes from the Rain, a Man Stood Atop a Stack Of \n
# Newspapers in Times Square. When the Newsstand'S Proprietor Asked\n
# If He Realized What He Was Standing on, He Replied, \"Of Course,\n
# These\nAre the Times That Dry Men'S Soles\".\n"