- Published
- Author
- Syed SibtainSystem Analyst
In Ruby,
Furthermore, using
#ruby #rubyonrails
attr_reader and attr_accessor are used to create getter and setter methods for class attributes. These are part of a group of methods (attr_* methods) that make it easier to create getter and setter methods for class attributes.attr_reader: Creates a getter method, allowing read-only access to an instance variable.Code
class Person
attr_reader :name
def initialize(name)
@name = name
end
end
person = Person.new("Sibtain")
puts person.name # Outputs: Sibtainattr_accessor: Creates both getter and setter methods, allowing read and write access to an instance variable.Code
class Person
attr_accessor :name
def initialize(name)
@name = name
end
end
person = Person.new("Sibtain")
puts person.name # Outputs: Sibtain
person.name = "John"
puts person.name # Outputs: JohnFurthermore, using
attr_reader and attr_accessor promotes encapsulation by controlling how the attributes of a class are accessed and modified.#ruby #rubyonrails