需要帮助在ruby中自定义类属性?

时间:2013-07-02 07:14:20

标签: ruby class methods rspec attributes

我正在尝试创建一个Book类,其中包含1个属性:title,如果以小写形式输入,则必须为大写。我的代码在repl.it中工作但是rspec仍然显示NoMethodError(未定义的方法'title'用于#(Book .... @ title =“Inferno”) 我的代码:

class Book
    def initialize(title=nil)
        @title = title
    end
    def title=(new_title)
        title = new_title.capitalize!

    end

end

Rspec的:

require 'book'

describe Book do

  before do
    @book = Book.new
  end

  describe 'title' do
    it 'should capitalize the first letter' do
      @book.title = "inferno"
      @book.title.should == "Inferno"
    end

谢谢。

2 个答案:

答案 0 :(得分:0)

试一试。

class Book

  attr_reader :title

    def initialize(title=nil)
      @title = title && title.capitalize!
    end

    def title=(new_title)
        @title = new_title && new_title.capitalize!
    end

end

答案 1 :(得分:-1)

class Book
  def initialize(title=nil)
    @title = title
  end

  def title=(new_title)
    title = new_title.capitalize!
    puts title
    puts @title
  end

  def title
    @title
  end

end

b = Book.new('hello')
b.title = 'hello'

--output:--
Hello
hello

@title和title是两个不同的变量。