2017-10-08 3 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という名前の行方不明ゲッター方法について文句を言うのに対して。

2番目のバージョンには、@title変数の ゲッターメソッドがありません。仕様書に「書かれているときに

def title 
    @title 
end 
+0

class Book attr_reader :title # ... end 

attr_reader :titleがあなたの最初のバージョンでのようにメソッドを生成し、ただのショートカットです:あなたは、このようなgetterメソッドを追加するattr_readerマクロを使用することができます"def title =(title)"を参照していますか? – naufragio

+1

これは、 "@ title.title =" "というタイトルのメソッドを参照しています。正しい! – spickermann