When does attr accessor is necessary?


#1

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
end

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

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
end
end

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


#2

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


#3

Edited.

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


#4

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
  end
end

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.


#5

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

Examples are the quotes in my post.


#8

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

def name
    @name 
end

is replaced by,

 attr_reader :name

#9

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