2

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?

Nakilon
  • 34,866
  • 14
  • 107
  • 142

1 Answers1

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