macsplean
macsplean

Reputation: 609

a method that changes the result of a setter

I am assigned to write some ruby code that will work with the following (segment of a) rspec test:

before do
  @book = Book.new
end

describe 'title' do
  it 'should capitalize the first letter' do
    @book.title = "inferno"
    @book.title.should == "Inferno"
  end

This is the solution, but I don't understand it:

class Book
  attr_reader :title

  def title=(new_title)
    words = new_title.split(" ")
    words = [words[0].capitalize] +
      words[1..-1].map do |word|
        little_words = %w{a an and the in of}
        if little_words.include? word
          word
        else
          word.capitalize
        end
      end
    @title = words.join(" ")
  end

end

I think I am correct to deduce that @book.title = "inferno" will run the title method and eventually create a new value for the @title variable at the bottom. I know that this causes @book.title to update to "Inferno" (capitalized), but I'm not sure why. Is this a case of def title being some sort of variable method, and @title being it's final value? That's my best guess at this point.

EDIT in case it's not clear, what I'm not understanding is why setting @book.title ='inferno' causes @book.title to update to "Inferno".

Upvotes: 0

Views: 78

Answers (2)

Bala
Bala

Reputation: 11244

Your understanding is almost correct. Here is a simple example

 class Chapter
   attr_reader :title
   def title=(new_title)
     @title = new_title.reverse
   end
 end

 @c = Chapter.new
 @c.title = "ybuR"
 @c.title #=> Ruby

Upvotes: 2

sites
sites

Reputation: 21795

When you have setter and getter methods in Ruby:

attr_writer :something
attr_reader :something

From my little understanding of this, these methods are equivalent to

def something=(value)
  @something = value
end

def something
  @something
end

Respectively.

Or in one statement, it could be:

attr_accessor :something

Anyway, what you are doing is to write the setter method yourself, capitalising each word of the string passed as an argument.

Upvotes: 2

Related Questions