In Ruby, you can define the initialize method in a class to set up the initial state of newly created objects. The attr method is used to define instance variables and generate getter and setter methods for them.
To define the initialize method and use attr in a class, you can follow these steps:
attr_accessor or attr_reader as per your requirement. Here's an example:main.rb167 chars9 linesIn the initialize method, you can pass arguments to set the attributes of the instantiated object. In this example, the initialize method takes two arguments: attribute1 and attribute2. The @ symbol is used to define and assign the instance variables.
Now you can create new instances of the class and set the attributes by using the new method:
main.rb41 chars2 lines
When creating an instance of MyClass, the initialize method will be automatically called and the provided values will be assigned to the respective attributes.
You can access and modify the attributes using the generated getter and setter methods:
main.rb120 chars5 lines
Keep in mind that the attr_accessor method generates getter and setter methods, while attr_reader only generates getter methods and attr_writer only generates setter methods for the defined attributes.
Note: It's a good practice to use attr_accessor, attr_reader, or attr_writer rather than using attr directly as it provides clearer intent and prevents accidental modification of attributes that should be read-only or write-only.
gistlibby LogSnag