Accessor methods automatically generate getter/setter methods for object instance variables (i.e. @variable
) with a single line of code (via metaprogramming):
class Person
def initialize(name)
@name = name
end
# creates getter/setter methods for `@name`
attr_accessor :name
end
person = Person.new("John")
puts person.name #=> "John"
person.name = "Wayne"
puts person.name #=> "Wayne"
The example above is equivalent to the following:
class Person
def initialize(name)
@name = name
end
def name
@name
end
def name=(val)
@name = val
end
end
person = Person.new("John")
puts person.name #=> "John"
person.name = "Wayne"
puts person.name #=> "Wayne"
Ruby has three types of accessor methods:
attr_reader
: generates only a getter for the given instance variables;attr_writer
: generates only a setter for the given instance variables;attr_accessor
: generates both, a getter and a setter for the given instance variables.
These are useful because they provide a shorter syntax than creating getter/setter methods manually for class instance variable.
It is possible to combine different accessor methods together in a single class, for example, like so:
class Person
def initialize(name, age)
@name = name
@age = age
end
# creates getter for `@age`
attr_reader :age
# creates getter/setter methods for `@name`
attr_accessor :name
end
person = Person.new("John", 29)
puts person.name #=> "John"
person.name = "Wayne"
puts person.name #=> "Wayne"
puts person.age #=> 29
In the example above, the @name
instance variable can be read or re-assigned, while the @age
instance variable can only be read. If you attempt to re-assign @age
, then an error will be thrown because a setter method does not exist for it:
# undefined method `age=' ... (NoMethodError)
person.age = 39
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.