【发布时间】:2026-02-15 05:00:01
【问题描述】:
我找不到这个问题的解决方案,我进行了研究以找到问题并解决它们,但还想不出任何答案。
我要做的是将字符串转换为标题大小写的字符串。
例如: 《指环王》>《指环王》
(如您所见,第一个单词总是大写的,如果是文章则无所谓,但如果字符串中有文章单词,则应该小写,如上例,并大写任何其他不是的单词)。
这是我要解决的练习的规范 (RSpec):
describe "Title" do
describe "fix" do
it "capitalizes the first letter of each word" do
expect( Title.new("the great gatsby").fix ).to eq("The Great Gatsby")
end
it "works for words with mixed cases" do
expect( Title.new("liTTle reD Riding hOOD").fix ).to eq("Little Red Riding Hood")
end
it "downcases articles" do
expect( Title.new("The lord of the rings").fix ).to eq("The Lord of the Rings")
expect( Title.new("The sword And The stone").fix ).to eq("The Sword and the Stone")
expect( Title.new("the portrait of a lady").fix ).to eq("The Portrait of a Lady")
end
it "works for strings with all uppercase characters" do
expect( Title.new("THE SWORD AND THE STONE").fix ).to eq("The Sword and the Stone")
end
end
end
这是我的尝试,到目前为止我所做的:
class Title
def initialize(string)
@string = string
end
def fix
@string.split.each_with_index do |element, index|
if index == 0
p element.capitalize!
elsif index == 1
if element.include?('Is') || element.include?('is')
p element.downcase!
end
end
end
end
end
a = Title.new("this Is The End").fix
p a
输出:
“这个”
“是”
=> ["This", "is", "The", "End"]
我想做什么:
- 创建一个名为 Title 的类并用一个字符串对其进行初始化。
- 创建一个名为 fix 的方法,到目前为止,只检查索引 0
@string.split的.each_with_index方法(循环 通过),并打印element.capitalize!(注意“砰”,即 应该修改原始字符串,正如您在输出中看到的那样 以上) - 我的代码所做的是检查索引 1(第二个字)和
调用
.include?('is')看第二个词是不是文章, 如果是(使用 if 语句),则调用element.downcase!, 如果没有,我可以为索引创建更多检查(但我意识到 这里是一些字符串可以由 3 个单词组成,另一些由 5 个单词组成, 其他人 10,依此类推,所以我的代码对此效率不高, 这是我无法解决的问题。
也许创建一个文章单词列表并使用 .include 进行检查?如果列表中有一些单词,方法是什么? (我试过这个,但 .include? 方法只接受字符串而不是数组变量,我试过 join(' ') 方法但没有运气)。
非常感谢! 真的!
【问题讨论】:
-
您可以通过使用
case语句或Set来匹配您想要小写的单词,从而大大消除这个问题。 -
我运行了你的代码,它返回了
["This", "is", "The", "End"],这与你发布的不符。 -
感谢@Jordan,它现在是最新的。
-
因为问题涉及改进(到目前为止)工作正常的代码,它可能更适合Code Review Stack Exchange。
-
你只关心索引 0 或索引不 0,不关心索引 1。