我有这个练习:
编写一个
Title
用字符串初始化的类。它有一种方法——
fix
应该返回字符串的标题大小写版本:
Title.new("a title of a book").fix
= 书名
您需要使用条件逻辑if
和else
语句来完成这项工作。
确保您仔细阅读测试规范,以便了解要实现的条件逻辑。您将要使用的一些方法:
String#downcase
String#capitalize
Array#include?
另外,这是 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
谢谢@simone,我采纳了你的建议:
class Title
attr_accessor :string
def initialize(string)
@string = string
end
IGNORE = %w(the of a and)
def fix
s = string.split(' ')
s.map do |word|
words = word.downcase
if IGNORE.include?(word)
words
else
words.capitalize
end
end
s.join(' ')
end
end
虽然我在运行代码时仍然遇到错误:
expected: "The Great Gatsby"
got: "the great gatsby"
(compared using ==)
exercise_spec.rb:6:in `block (3 levels) in <top (required)>'
从我初学者的角度来看,我看不出我做错了什么?
最终编辑:我只想对大家早先为我提供帮助所付出的所有努力表示感谢。我将展示我能够生成的最终工作代码:
class Title
attr_accessor :string
def initialize(string)
@string = string
end
def fix
word_list = %w{a of and the}
a = string.downcase.split(' ')
b = []
a.each_with_index do |word, index|
if index == 0 || !word_list.include?(word)
b << word.capitalize
else
b << word
end
end
b.join(' ')
end
end