attr_accessor
attr_accessor creates the ways to read and change a value on an object in a single line, like putting a window and a door on a box. Without it you would write each one by hand.
In this page:
Syntax
class ClassName
attr_accessor :attribute
attr_reader :read_only
attr_writer :write_only
end
attr_accessor
attr_accessor :name automatically generates both a getter (name) and setter (name=) method for an instance variable, saving you from writing them manually.
attr_reader generates only a getter, and attr_writer generates only a setter, for when you want to restrict read or write access. This is one of Ruby's most commonly used metaprogramming conveniences.
Note:
Use attr_reader for read-only properties you don't want external code to modify directly.
Example: attr_accessor
class Product
attr_accessor :name, :price
def initialize(name, price)
@name = name
@price = price
end
end
p = Product.new("Pen", 2.5)
puts p.name
p.price = 3.0
puts p.price
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Assigning inside a method with
name = "x"and expecting the attribute to change, when it creates a local variable; useself.name = "x". - Using
attr_accessorwhen only reading is needed, whenattr_readeris safer. - Writing
attr_accessor namewithout the colon, which looks for a variablename.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: