我对编程非常陌生,需要一些帮助来理解一些概念。我正在尝试为类Book创建一个方法,但不断得到“无标题=方法”错误。如何或如何初始化以修复此错误?
Rspec代码
before do
@book = Book.new
end
describe 'title' do
it 'should capitalize the first letter' do
@book.title = "inferno"
@book.title.should == "Inferno"
end
这是我的代码
class Book
def title(string)
string.downcase!
string_temp = string.split
small_words = ["a", "an", "the", "at", "by", "for", "in", "of", "over",
"on", "to", "up", "and", "as", "but", "it", "or", "nor"]
string_temp.map{|word| word.capitalize! unless small_words.include?(word)}
string_temp[0].capitalize!
string_temp.join(" ").strip
end
end
答案 0 :(得分:2)
只需创建title=
和title
方法:
class Book
def title=(string)
@title = string
end
def title
@title
end
end
这与
相同class Book
attr_writer :title
attr_reader :title
end
这甚至可以简化为
class Book
attr_accessor :title
end
但是你可能会为作者提供一个自定义实现:
class Book
def title=(string)
@title = titleize(string)
end
attr_reader :title
private
def titleize(string)
#...
end
end