What is the difference between attr_accessor, attr_reader, and attr_writer?
Last updated
They are macros that generate accessor methods for instance variables: attr_reader makes a getter, attr_writer makes a setter, and attr_accessor makes both. They exist to avoid hand-writing repetitive getter/setter methods.
attr_reader :x: Generatesxreturning@x; read-only.attr_writer :x: Generatesx=to set@x; write-only.attr_accessor :x: Generates both getter and setter.Practical notes:
Default to the least access needed (often
attr_reader) to protect internal state.Inside the object, assigning to a writer needs
self.x = ...since a barex = ...creates a local variable.
[lang:ruby]
class User
attr_accessor :name # name and name=
attr_reader :id # id only
def initialize(id) = @id = id
end
- https://medium.com/@davidwenzel/ruby-attr-reader-attr-writer-and-attr-accessor-differences-use-cases-and-examples-9853be3179f2
- https://dev.to/bdavidxyz/ruby-attraccessor-attrwriter-and-attrreader-4le
- https://www.freecodecamp.org/news/learning-ruby-from-zero-to-hero-90ad4eecc82d/
- https://docs.ruby-lang.org/en/3.4/Module.html
- https://ruby-doc.org/core-2.4.7/Module.html
- https://docs.ruby-lang.org/en/3.4/NEWS/NEWS-3_0_0_md.html
- https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/accessors.html
- https://docs.rubocop.org/rubocop/latest/cops_style.html