-1

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?

Boris Stitnicky
  • 12,444
  • 5
  • 57
  • 74
Fengson
  • 4,751
  • 8
  • 37
  • 62

4 Answers4

2

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.

toro2k
  • 19,020
  • 7
  • 64
  • 71
1

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
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

You can use also attr_accessor (or attr_reader and attr_writer)

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
merkushin
  • 481
  • 9
  • 17
1

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
lalameat
  • 754
  • 3
  • 10