When does attr accessor is necessary?


Hello guys !

I’m on page 5 of OOProgramming II.
I’m discovering attr accessors, but I can’t understand when they are required and when they are not.

This was an old example in OO I :

class Language
def initialize(name, creator)
@name = name
@creator = creator

def description
puts "I’m #{@name} and I was created by #{@creator}!"

See, there is no attr accessors.

In OO II, it is needed, i don’t understand why :

class Person
attr_reader :name
attr_writer :name
def initialize(name)
@name = name

If “Ruby needs methods in order to access attributes”, why is there no attr neither method to introduce variables @name and @creator in the first example ?
Because, in the second example, we used attr to introduce @name

Thanks for your help, have a nice day !

Link of the page of the second example : https://www.codecademy.com/courses/learn-ruby/lessons/object-oriented-programming-ii/exercises/attrreader-attrwriter?page=5


Please post a link to this exercise so we are all on the same page as you. Thanks.



-> https://www.codecademy.com/courses/learn-ruby/lessons/object-oriented-programming-ii/exercises/attrreader-attrwriter?page=5


Recall that in the earlier lesson we have methods to return the name and the job of the given instance. attr_reader replaces those methods with the built in one.

class Person
  attr_reader :name
  attr_reader :job
  attr_writer :job
  def initialize(name, job)
    @name = name
    @job = job

joe = Person.new('Joe','Programmer')
puts "Name: #{joe.name}"
joe.job = "Writer"
puts "Job : #{joe.job}"
Name: Joe
Job : Writer

In the above code, .job and .name are methods, still, but accessor methods that we didn’t have to write into our class.


Alright, but why attr accessors are necessary in the second example but not in the first ?

Examples are the quotes in my post.


Because in the second example there are no methods for name or job so they cannot be accessed.

def name

is replaced by,

 attr_reader :name


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.