Certainly! In Ruby, attr_accessor is a convenient way to define getter and setter methods for instance variables of a class. It allows you to read and write the values of these variables with ease. Let's break it down with an example:
Suppose you have a Person class and you want to create instances with attributes like name and age. You can use attr_accessor to define getter and setter methods for these attributes.
Here's an example:
ruby
class Person
# Define getter and setter methods for the 'name' attribute
attr_accessor :name
# Define getter and setter methods for the 'age' attribute
attr_accessor :age
# Constructor to initialize the attributes
def initialize(name, age)
@name = name
@age = age
end
end
# Create a new instance of the Person class
person = Person.new("Alice", 30)
# Access and modify attributes using the getter and setter methods
puts "Name: #{person.name}" # Read 'name'
puts "Age: #{person.age}" # Read 'age'
person.name = "Bob" # Set 'name'
person.age = 25 # Set 'age'
puts "Updated Name: #{person.name}"
puts "Updated Age: #{person.age}"
In this example:
We define a
Personclass with two attributes:nameandage.We use
attr_accessorto create getter and setter methods for both attributes. This eliminates the need to write custom methods to access and modify these attributes.In the constructor (
initializemethod), we set the initial values ofnameandagewhen creating a newPersonobject.We create an instance of the
Personclass and access thenameandageattributes using the getter methods (person.nameandperson.age) and set their values using the setter methods (person.name =andperson.age =).
Here's what happens when you run this code:
- We create a
Personobject with the name "Alice" and age 30. - We print the initial values of
nameandage. - We update the values of
nameandage. - We print the updated values.
The attr_accessor creates getter and setter methods for the instance variables @name and @age, allowing you to read and modify them as if they were public attributes of the class. This simplifies your code and follows the principle of encapsulation by controlling access to instance variables through methods.
Comments
Post a Comment