Question

I have to add getters and setters to a class Book that looks like this :

class Book
  def initialize (title, author, pages, year)
    @title = title 
    @author = author 
    @pages = pages 
    @year = year
  end
end

The problem is I am not allowed to use def. Is it possible somehow? The only way I know is to use:

def change_name(name)
  @name = name
end

for a setter. I don't even know how a getter should look like. Any help?

Was it helpful?

Solution

Ruby let you define simple getters/setters using the methods attr_accessor, attr_reader, and attr_writer. In your example you can use attr_accessor to define both a getter and a setter for your instance variables:

class Book

  attr_accessor :title, :author, :pages, :year

  def initialize (title, author, pages, year)
    # same as before...
  end
end

book = Book.new('foo', 'bar', 100, 2010)
book.title
# => "foo"

book.title = 'baz'
book.title
# => "baz"

Calling attr_accessor :title is equivalent to define a couple of methods like the following:

def title
  @title
end

def title=(new_title)
  @title = new_title
end

You can find more informations about assignment methods (i.e. methods whose name end in =) on the Ruby documentation.

OTHER TIPS

Use attr_accessor:

class Book
  attr_accessor :title, :author, :pages, :year
  def initialize (title, author, pages, year)
    @title = title 
    @author = author 
    @pages = pages 
    @year = year
  end
end

You can use also attr_accessor (or attr_reader and attr_writer)

Use define_method to define your method dynamically. In this case, directly using attr_accessor also should work. It will define getter and setter for you implicitly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top