我无法找到解决此问题的解决方案,我做了一项研究以找到问题并修复它们,但无法想出任何答案。在Ruby中修改数组项目(如果它包含特定单词)
我想要做的是将字符串转换为标题套用字符串。
例如: “魔戒三部曲”>“的指环王”
(正如你所看到的,第一个单词总是大写,它不会,如果是无关紧要一篇文章,但如果字符串中有文章词语,应该用小写字母表示,如上例所示,并且大写其他任何不是的单词)。
这是规范(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”
“是”
=> [ “这”, “是”, “该”, “结束”]
我试图这样做:
- 创建一个名为Title的类并用一个字符串初始化它。
- 创建一个名为修复方法,到目前为止,只为指数检查0 的
@string.split
与方法.each_with_index
(循环 通过),并打印element.capitalize!
(注意是“砰”,即 应该修改原始字符串,你可以看到它的输出上面 ) - 我的代码确实是检查索引1(第二个字)和 调用
.include?('is')
,看看第二个字的文章, 如果是(与if语句)element.downcase!
被调用, 如果不是,我可以创建更多的索引检查(但我意识到 这里有些字符串可能由3个字组成,其他字符由5个, 其他由10等等组成,所以我的代码效率不高, 这是我无法解决的问题。
也许创建一个文章词汇列表并检查.include?方法,如果有一些单词的名单? (我试过这个,但.include?方法只接受一个不是数组变量的字符串,我尝试了join(' ')
方法,但没有运气)。
非常感谢! 真的是!
你可以通过使用'case'语句或'Set'来匹配你想要的小写字母来清理它。 – tadman 2015-01-20 23:09:38
我运行了你的代码,它返回了'[“This”,“is”,“The”,“End”]',这与你发布的内容不符。 – 2015-01-20 23:14:46
谢谢@Jordan它现在是最新的。 – bntzio 2015-01-20 23:16:51