dimanche 23 avril 2017

Ruby test about classes, and changing a variable, has me stuck. (I assume VERY simple)

I don't understand what to do, or how to solve this.

#This is the test
require 'book'

   describe Book do

   before do
   @book = Book.new
   end

   describe 'title' do
   it 'should capitalize the first letter' do
   @book.title = "inferno"
   expect(@book.title).to eq("Inferno")
   end

end

I've tried things like this:

class Book
   def title string
        @title = string.to_s.capitalize
   end
end

@book = Book.new
puts @book.title("inferno")

This works, but fails the test since the test wants:

@book.title = "inferno"

But everything I've tried with the above line of code fails and I get an error message stating in some way:

"undefined method 'title=' for #<Book" etc

I don't understand how I can just try to change the value of a variable within a class with an "=" in the open like that. I really don't understand what's going on. I think I'm simply too uneducated at the moment to solve this.

I've seen someone do this online

class Book
   def title
      @title
   end

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

But I have no idea what's going on. Why is there an argument following an "="?

Why is there a 'title' method, then a 'title='?

What is @title = titlieze(title) doing?

Looking at this code, I can't even reverse engineer it and understand what's happening.

If anyone can give me some insights into any of this, I would be extremely grateful.

Aucun commentaire:

Enregistrer un commentaire