Lazily Initialized Attributes
Initialize an attribute on access instead of at construction time.
class Employee class Employee
def initialize def emails
@emails = [] => @emails ||= []
end end
end end
Motivation
The motivation for converting attributes to be lazily initialized is for code readability purposes. While the above example is simple, if the Employee class has multiple attributes that need to be initialized the constructor will need to contain all the initialization logic. However, lazily initialized attributes can encapsulate all their initialization logic within the methods themselves.
Mechanics- Move the initialization logic to the attribute getter.
- Test
Example
The code below is an Employee class with the email attribute initialized in the constructor.
class Employee
attr_reader :emails
def initialize
@emails = []
end
end
Moving to a lazily initialized attribute generally means moving the initialization logic to the getter method and initializing on the first access.
class Employee
def emails
@emails ||= []
end
end
Read: Ruby: Lazily Initialized Attributes