I have seen attr_reader and attr-writer and attr_accessor used in Ruby programs as if they were Object methods (or Kernel methods mixedin to Objest). However attr_reader and attr-writer and attr_accessor are part of a class called Module and I don't understand how they can be used in all classes, what makes them available to be used?
Asked
Active
Viewed 1,272 times
2
-
What is attr-reader? What is calss? What is attr-writer? What is Objest? – sawa Sep 05 '14 at 23:57
-
Classes are modules, actually. In fact, the class called `Class` is a subclass of the class called `Module`. – Silvio Mayolo Apr 10 '22 at 00:25
1 Answers
2
It works like this:
module Attr
attr_accessor :my_variable
end
class MyClass
@my_variable = "hi"
def initialize
@my_variable = "ho"
end
end
You include
the module in the class to construct an accessor for the instance variable @my_variable
:
MyClass.include Attr
c = MyClass.new
c.my_variable #=> "ho"
c.my_variable = "huh?" #=> "huh?"
c.my_variable #=> "huh?"
You extend
the module to the class to construct an accessor for the class instance variable @my_variable
:
MyClass.extend Attr #=> MyClass
MyClass.my_variable #=> "hi"
MyClass.my_variable = "nuts" #=> "nuts"
MyClass.my_variable #=> "nuts"
c.my_variable #=> "huh?"
As you see, the instance variable @my_variable
is distinct from the class instance variable @my_variable
. They coexist just as they would if they had different names.
More commonly, you'll see include
and extend
within the class definition, but the effect is the same as what I have above:
class MyClass
include Attr
extend Attr
@my_variable = "hi"
def initialize
@my_variable = "ho"
end
end

Cary Swoveland
- 106,649
- 6
- 63
- 100