Ruby – Accessor Methods

Objects and Attributes

We introduce states into an object through the initialize method. Other than creating an object, it is important to also be able to access and manipulate the state of an object.

One way to do that is to write accessor methods

Getter Function

class Book

def initialize(isbn, price)

@isbn = isbn

@price = Float(price)

end

#creating an accessor method for isbn

def isbn

@isbn

end

#creating an accessor method for price

def price

@price

end

end

#Result

book = Book.new(“isbn”, 12.34)

puts “ISBN = #{book.price}”

puts “Price = #{book.price}”

#ISBN = isbn

#Price = 12.34

By defining the isbn and price (accessor) method, it will return the instance variable @isbn and @price.

For ruby, there is a shortcut for these accessor methods.

attr_reader :isbn, :price

The symbol “:” provides a way of referencing a name.

name -> :isbn

value -> isbn

instance variable -> @isbn

Setter Function

To set an attribute from outside the object, we create a method who name ends with an equal sign.

class Book

def initialize(isbn, price)

@isbn = isbn

@price = Float(price)

end

def price=(new_price)

@price = new_price

end

#...

end

book = Book.new("isbn1", 33.80)

puts "ISBN = #{book.isbn}

puts "Price = #{book.price}

book.price = book.price * 0.75

puts "New price = #{book.price}"

ISBN = isbn1

Price = 33.8

New price = 25.3499999998

The assignment book.price = book.price * 0.75 invoke the method price= in the book object, passing it the discounted price as an argument.

For ruby, there is a shortcut for these write-only accessor methods. (attr_writer) but it is rare that you only use the write-only method. Instead use,

attr_reader :isbn

attr_accessor :price

 To make things a lot simpler, the shortcut accessor methods are translated as below.
#attr_reader

def var
@var
end

#attr_writer

def var=(change)
var=change
end

#attr_accessor

def age=(value)
@age = value
end

def age
@age = age
end