2017-10-08 27 views
0

这是odin项目的一个练习,他们给你一个带有测试规范的文件,你必须编写程序来传递它们。Ruby类如何工作

程序的工作,但我刚开始Ruby类,我不明白为什么,如果我做了修改,我会告诉不起作用:

Rspec的

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 

    it 'should capitalize every word' do 
     @book.title = "stuart little" 
     @book.title.should == "Stuart Little" 
    end 

    describe 'should capitalize every word except...' do 
     describe 'articles' do 
     specify 'the' do 
      @book.title = "alexander the great" 
      @book.title.should == "Alexander the Great" 
     end 

     specify 'an' do 
      @book.title = "to eat an apple a day" 
      @book.title.should == "To Eat an Apple a Day" 
     end 
     end 

     specify 'conjunctions' do 
     @book.title = "war and peace" 
     @book.title.should == "War and Peace" 
     end 

     specify 'the first word' do 
     @book.title = "the man in the iron mask" 
     @book.title.should == "The Man in the Iron Mask" 
     end 
    end 
    end 
end 

代码

class Book 
    def title 
    @title 
    end 

    def title=(title) 
    @title = titlieze(title) 
    end 

    private 
    def titlieze(title) 
    stop_words = %w(and in the of a an) 
    title.capitalize.split.map{|w| stop_words.include?(w) ? w : w.capitalize}.join(' ') 
    end 

end 

为什么,如果我写我这样的代码

class Book 

    def title=(title) 
    @title = titlieze(title) 
    @title 
    end 

    private 
    def titlieze(title) 
    stop_words = %w(and in the of a an) 
    title.capitalize.split.map{|w| stop_words.include?(w) ? w : w.capitalize}.join(' ') 
    end 

end 

然后我得到这个错误:

Failure/Error: expect(@book.title).to eq("Inferno") 

    NoMethodError: 
     undefined method `title' for #<Book:0x000000017bd0a8 @title="Inferno"> 
     Did you mean? title= 

但这种方法“标题”没有定义?为什么它说不是?

回答

2

因为def title=(title)定义了设置器方法名为title=@title变量赋值。重要的是要注意=是方法名称的一部分。

虽然说明书抱怨缺少获取方方法名为title(没有=)。

您的第二个版本缺少titlegetter方法为@title变量。你可能只是使用attr_reader宏添加这样一个getter方法:

class Book 
    attr_reader :title 

    # ... 
end 

attr_reader :title仅仅是在你的第一个版本生成的方法等的快捷方式:当在规范中写着“

def title 
    @title 
end 
+0

所以期望(@ book.title)“我指的是方法”def标题,而当它写成“@ book.title =”inferno“”我指的是方法“def title =(title)”? – naufragio

+1

这就是正确! – spickermann