What are attr_reader and attr_accessor in Ruby?
When we define a class
in ruby, we typically add a few instance variables to the class. In order to read and write those instance variables outside of the class, we add getter and setter instance methods to the class (and you may have seen these other programming languages like C++ and Java). It looks something like this:
class Person
def name
@name
end
def name=(your_name)
@name = your_name
end
end
person = Person.new
person.name = "Jim"
person.name # => "Jim"
In ruby, we don't have to add these getters/setters manually. Ruby does that for us automatically (it dynamically adds those methods to our class using metaprogramming at runtime). All Ruby needs to know is the name of the instance variables we wish to set up. And it can add methods matching those names.
attr_reader
adds a getter only. attr_accessor
adds a getter and setter both. (There is also attr_writer
to add a setter method only).
With attr_accessor
, the above code can become:
class Person
attr_accessor :name
end
Note that attr_accessor :name
is not some special syntax in ruby. It is a method call (on the Module
class, but we won't worry about that here) with one parameter - the ruby symbol :name
. Rewriting it with parens would look like this:
class Person
attr_accessor(:name)
end
We can see that the appropriate instance methods are added with
> Person.instance_methods
=> [:name=,
:name,
...
]
That's all there is to it. You can write attr_accessor
in your class and never worry about manually adding the boilerplate code for reading and writing the value of an instance variable.
Extra
(a bit more advance concept. You can skip for now if you're new to ruby)
How do all ruby classes have access to these special methods attr_accessor
? Where do they come from?
[todo: add details]