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.