5. attr_reader & attr_writer


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
  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!"
  private   # This method can't! Is for your classes
  def bank_account_number
    @account_number = 12345
    puts "My bank account number is #{@account_number}."

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


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?


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?


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


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



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


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

def job=(new_job)
@job = new_job

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


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


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)

def travail=(nouveau_travail)
@job= nouveau_travail