Ruby类如何工作

时间:2017-10-08 10:54:10

标签: ruby

这是来自odin项目的练习,他们为您提供了一个包含测试规范的文件,您必须编写程序才能通过它们。

该程序正在运行,但我刚刚开始使用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=

但方法&#34;标题&#34;定义没有?为什么它说它不是?

1 个答案:

答案 0 :(得分:2)

因为def title=(title)定义了名为title= setter 方法,以便为@title变量赋值。值得注意的是,=是方法名称的一部分。

虽然规范抱怨缺少名为title getter 方法(没有=)。

您的第二个版本缺少title变量的@title getter 方法。您可以使用attr_reader宏添加这样的getter方法:

class Book
  attr_reader :title

  # ...
end

attr_reader :title只是一个生成第一个版本的方法的快捷方式:

def title
  @title
end