【问题标题】:Can't understand class method & initializing无法理解类方法和初始化
【发布时间】:2014-12-12 19:23:02
【问题描述】:

我对编程很陌生,需要一些帮助来理解一些概念。我正在尝试为 Book 类创建一个方法,但不断收到“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

【问题讨论】:

    标签: ruby class methods


    【解决方案1】:

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

    【讨论】:

    • 非常感谢!这是有道理的。
    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2012-08-01
    • 2012-10-10
    • 2015-11-23
    • 2011-09-28
    相关资源
    最近更新 更多