What are Attributes in Ruby?

Attributes in Ruby:

In Ruby, an object that is totally secretive is pretty useless. You can create it, but then you can’t do anything with it. You’ll normally define methods that let you access and manipulate the state of an object, allowing the outside world to interact with the object. These externally visible facets of an object, called its attributes.

Types of Attributes in Ruby:

There are mainly two types of Attributes in Ruby:
i. Writable Attributes: These attributes allow one to set an attribute from outside the object.
ii. Virtual Attributes: These attribute-accessing methods do not have to be just simple wrappers around an object’s instance variables.

Ruby’s attributes:

  • the method of attr
  • the method attr reader
  • the method attr writer
  • the method attr accessor

attr_reader:

attr_reader can only read the value, but not change it.

attr_writer:

attr_writer creates an instance variable and a setter method for each attribute name passed as an argument.

attr_accessor:

attr_accessor creates an instance variable, a getter, and a setter method for each attribute name passed as an argument.

Benefits of using Attributes in Ruby:

1. Ruby attributes are like variables that can be used in Ruby code. Attributes defined with the attr_accessor method and then assigned values using the attr_set or attr_get method.

2. Ruby attributes have been used in many different ways for different purposes, such as in ids, ids for objects, ids for methods, ids for classes and methods, ids for arrays and objects.