5. attr_reader & attr_writer


#1

Can someone please give an example how to use this using the code from lesson 1. I've spent a few days trying to wrap my head around this and still can't grasp the concept. I understand how to do it and can pass, but would like to understand. The lesson even said to refer to the code from lesson 1, but when they use a different code as an example in the editor. I'm thinking it would have been easier if they stuck with the code from the first example, at least for me.

  class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
  
  public# This method can be called from outside the class.
        # Used for methods.
  
  def about_me
    puts "I'm #{@name} and I'm #{@age} years old!"
  end
  
  private   # This method can't! Is for your classes
  
  def bank_account_number
    @account_number = 12345
    puts "My bank account number is #{@account_number}."
  end
end

eric = Person.new("Eric", 26)
eric.about_me
eric.bank_account_number

#2

I'm not exactly sure what you're asking. Are you asking for a way to implement attr_reader and attr_writer in the code you provided?


#3

I don't understand this lesson. They said to look back at lesson one for example, that if we want to access @name that we have to write a method for it. Basically i was wondering how we would apply the attr to lesson 1?


#4

PS. The code I posted above is from lesson 1 in Object Oriented Programming II


#5

But I can't find anything in the instructions that makes a comparison with lesson 1.

Anyway, if you want to use the accessors in lesson 1, it really depends on what you want to do. If you want to have accessors for @age for example, you could use:

attr_reader :age

and/or

attr_writer:age

or just

attr_accessor :age

If you want to create a new attribute, then you also can, you would simply need to change the name used in the accessor:

attr_reader :your_attribute

#6

I'm new to ruby to and was trying to understand this the best way is to test the class ex:
first write
attr_reader :name
attr_writer :job

then erase this line since attr_reader and attr_writer does the same thing this respectively
def name
@name
end

def job=(new_job)
@job = new_job
end


then write
aaa = Person.new("name", "job")
then call for the variables

aaa.name

check the results
you can test this by changing or removing the attr_


#7

Hi, Guys,

It was tough to know how to handle but eventually my code works
class Personne

attr_reader :nom
attr_writer :travail

def initialize(nom)
@nom=nom
end

def travail=(nouveau_travail)
@job= nouveau_travail
end
end