Confused about attr_reader & writer

So as I am finishing the Ruby tutorial I’m kinda confused about attr_reader and attr_writer first of all why would I ever have to use attr_reader? for example

class Rabbit
  def initialize(name)
    @name = name
  end
end

rab = Rabbit.new("Steve")

now if I wanted to “read” name, can’t I just write something like “puts rab.name”? why do I need attr_reader for that

Same goes for attr_writer, if I wanted to change the value of rab = Rabbit.new("Steve"), why not just like this; rab.name = "newName"

Well, attr_reader and attr_writer are similar to private and public constructors.

You use private and public for methods. So with private and public you can make methods accessible or not outside of the class.

With instance variables, you can make them accessible or not with attr_reader and attr_writer outside of the class.

Let’s use this example:

class Person
  def initialize(name)
    @name = name
  end
end
Let's say you create one Person
p1 = Person.new("Dave")

With the above class there is no way to change the name DAve to anything else. You would need to create another Person object with a different name. Sometimes that is what you want and by not using attr_reader and attr_writer you can do that.

Now let’s look at this:

class Dog
  attr_reader :name
  attr_writer :name
  def initialize(name)
    @name = name
  end
end

Now we can change the name of the object Dog(p1.name = “Other Name”) without having to create another Dog object. :slight_smile:

But you can use methods for reaching instance variables instead of attr_reader and attr_writer but that is not Ruby best practice,

Last Example using methods instead of attr_reader and attr_writer,

class Car
  def initialize(model)
    @model = model
  end

  def model 
    @model
  end

  def model=(value)
    @model = value
  end
end
2 Likes

So basically with this code

`class Person
  def initialize(name)
    @name = name
  end
end
Let's say you create one Person
p1 = Person.new("Dave")`

I couldn’t just write p1.name = “newName” because there is no .name method yet right? I was just confused because previously we simply assigned values with dot notation, which is fine for variables outside of a class but doesn’t work for variables inside one am I getting this right?

So if I had

hash = {
  value1 = 1
  value2 = 2
  value3 = 3
}

To update it I would have written

hash[value1] = 5

Just realized it wasn’t dot notation but brackets, to update a hash not a varbiale

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