In Ruby, getters and setters are methods that allow controlled access to an object's attributes. They're fundamental to Ruby Encapsulation, providing a way to read and modify an object's state.
Getters are methods that retrieve the value of an instance variable. They're also known as accessor methods.
class Person
def initialize(name)
@name = name
end
def name
@name
end
end
person = Person.new("Alice")
puts person.name # Output: Alice
Setters, also called mutator methods, allow you to change the value of an instance variable.
class Person
def name=(new_name)
@name = new_name
end
end
person = Person.new("Bob")
person.name = "Charlie"
puts person.name # Output: Charlie
Often, you'll want both getter and setter methods for an attribute. Here's how to implement both:
class Person
def initialize(name)
@name = name
end
def name
@name
end
def name=(new_name)
@name = new_name
end
end
person = Person.new("David")
puts person.name # Output: David
person.name = "Eve"
puts person.name # Output: Eve
Ruby provides a shortcut for creating both getter and setter methods using attr_* Methods:
class Person
attr_accessor :name
def initialize(name)
@name = name
end
end
person = Person.new("Frank")
puts person.name # Output: Frank
person.name = "Grace"
puts person.name # Output: Grace
attr_reader
for read-only attributes.attr_writer
for write-only attributes (rare, but possible).While attr_accessor
is convenient, custom getters and setters are useful for:
class Person
attr_reader :age
def age=(new_age)
if new_age >= 0 && new_age <= 120
@age = new_age
else
raise ArgumentError, "Age must be between 0 and 120"
end
end
end
person = Person.new
person.age = 30 # Valid
person.age = 150 # Raises ArgumentError
By mastering getters and setters, you'll enhance your ability to create robust and maintainable Ruby Ruby Classes and Ruby Objects.