【发布时间】:2015-02-02 19:39:19
【问题描述】:
我有这个练习:
编写一个用字符串初始化的
Title类。它有一个方法——
fix——它应该返回字符串的标题大小写版本:
Title.new("a title of a book").fix= 书名
您需要使用条件逻辑 -if和else语句 - 来完成这项工作。
请务必仔细阅读测试规范,以便了解要实现的条件逻辑。您将要使用的一些方法:
String#downcaseString#capitalizeArray#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
【问题讨论】:
-
测试规范是什么?
-
我不喜欢这种“再次发明圈子”的任务。这就是为什么我们有apidock.com/rails/String/titleize
-
您确定
include?是您想要的吗?例如,Theodore应该是大写还是小写?现在你说的是小写。 -
除了titleize不是他所追求的
-
不要用你的答案代替问题,这会使问题变得无用
标签: ruby string title-case