简体   繁体   中英

Classes, Objects, and setter methods in Ruby?

Trying to understand how to use setter methods Why am I getting a failure here? I don't understand what I'm doing wrong. Can someone please explain? Thanks.

class Book
  def title=(title)
    @title = title.capitalize
  end
end

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
  end
end

Test Failure:

Book title should capitalize the first letter Failure/Error: @book.title.should == "Inferno"

NoMethodError:

  undefined method `title' for #<Book:0x00000104abd538 @title="Inferno"> # ./ct.rb:865:in `block (3 levels) in <top (required)>' 

When you do:

@book.title.should == "Inferno"

you are essentially calling the title method on a Book object, which of course does not exist. You only defined the setter .

You also have to define the getter :

class Book
  def title
    @title
  end

  # ...
end

Note that there is a shorthand for defining both the setter and the getter:

class Book
  attr_accessor :title
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM