Wednesday, August 5, 2009

Ruby Setter and Getter Methods

class Person

def initialize(name,age)

@name = name

@age = age

end

def name=(name)

@name = name

end

def age=(age)

@age = age

end

def name

@name

end

def age

@age

end

can be written with
class Person

attr_accessor :name, :age

def initialize(name,age)

@name = name

@age = age

end

By using attr_accessor, you will automatically get the setter and getter method. Take note that there are some hashes following it.

If you only want the setter method, go for attr_writer, while the getter method, go for attr_reader.

While it is also possible to use attr :name to get attr_reader, and attr :name, true to get the same effect as attr_accessor, but it looks less readable than the previous ones.

Using setter, the set method becomes similar to variable assignment when it's actually a method call.