我正试图通过这个rspec
describe "title" do
it "should capitalize the first letter" do
@book.title = "inferno"
expect(@book.title).to eq("Inferno")
end
it "should capitalize every word" do
@book.title = "stuart little"
expect(@book.title).to eq("Stuart Little")
end
使用此代码
class Book
attr_accessor :title
def initialize(title="")
@title = capital(title)
end
def capital(title)
articles = %w(the a an and of in the)
new_title = []
title.split.each do |w|
articles.include?(w)? new_title << w : new_title << w.capitalize
end
new_title[0] = new_title[0].capitalize
new_title.join(" ")
end
end
book = Book.new("stuart little")
puts book.title
当我运行代码时,我得到“Stuart Little”,但是当我通过rspec运行它时,我一直收到错误。 (例如,它只是以“stuart little”的形式返回)。
我很清楚为什么会发生这种情况,所以我希望有人可以为我提供一些启示。
答案 0 :(得分:1)
当您为capital
方法分配标题时,您只运行new
方法,而不是在将其分配给title=
setter方法时运行。
我会将attr_accessor
替换为attr_reader
并添加自定义title=
setter方法:
class Book
attr_reader :title
def initialize(title = '')
self.title = title # calls the setter below
end
def title=(title)
@title = capital(title)
end
private
def capital(string)
articles = %w( a an and in of the )
words = title.split.map do |word|
articles.include?(word) ? word : w.capitalize
end
words.join(' ').capitalize
end
end