Ruby Can';我不懂课堂教学法;初始化

Ruby Can';我不懂课堂教学法;初始化,ruby,class,methods,Ruby,Class,Methods,我对编程非常陌生,需要一些帮助来理解一些概念。我正试图为类目创建一个方法,但一直出现“no title=method”错误。如何或如何初始化以修复此错误 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 这是我

我对编程非常陌生,需要一些帮助来理解一些概念。我正试图为类目创建一个方法,但一直出现“no title=method”错误。如何或如何初始化以修复此错误

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

只需创建
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

非常感谢!这是有道理的。