12. The Marriage of Modules and Classes


#1

https://www.codecademy.com/en/courses/ruby-beginner-en-zfe3o/2/1?curriculum_id=5059f8619189a5000201fbcb

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
end

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

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

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.


#4

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

attr_reader :name is equivalent to

def name
  @name
end

attr_writer :name is equivalent to

def name=(new_name)
  @name = new_name
end

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