attr_accessor
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: