I’m confused with Ruby’s attr_writer.
I’m trying to add a value inside an array but i’m encountering the following error:
Line 13: undefined method `test’ for # (NoMethodError)
class Pet
attr_writer :test
def initialize()
@test = []
end
end
pet = Pet.new()
pet.test << "Test was a pet"
Why? As I understand it, attr_writer is equivalent to a setter method.
Please explain. Thank you.
Yes,
attr_writerdefines a setter method. But your code tries to use a getterHere’s how ruby sees it (more or less)
If you actually set an array, it will work
As a side note: I personally consider write-only properties as a code smell. Something is probably wrong here. I have never had to use write-only attributes in my career.