12. The Marriage of Modules and Classes


Earlier lessons stressed that if you write “attr_reader :name” then you won’t have to take the time to write out:

def method(name)
@name = name

However, this lesson seems to throw that out the window by writing:

attr_reader :name
def initialize(name)
@name = name

Why the redundancy? Confused, I deleted the “attr_reader :name” line in the 2 places it shows up in the code, then clicked Save & Submit Code. The code seemed to function exactly as intended with no errors.

Am I misunderstanding how the three attr_ things work? And I’m forced to describe them as “the three attr_ things” since none of the lessons described what they are. For example, describing them by saying, “Well, no longer! We can use attr_reader to access a variable and attr_writer to change it.” So I’m not sure how to describe them collectively. The three attr_ methods? The three attr_ actions? Who knows.

There are readers and writers. To get both, you use an accessor.

attr_reader :name is equivalent to

def name

attr_writer :name is equivalent to

def name=(new_name)
  @name = new_name

attr_accessor :name will give you both of the method definitions above at the same time.