This post originated from an RSS feed registered with Ruby Buzz
by Jay Fields.
Original Post: Ruby: Lazily Initialized Attributes
Feed Title: Jay Fields Thoughts
Feed URL: http://blog.jayfields.com/rss.xml
Feed Description: Thoughts on Software Development
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.
classEmployee attr_reader:emails
definitialize @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.