Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. Modules and Namespaces > 9.8. Initializing Instance Variables Defined by a M...

9.8. Initializing Instance Variables Defined by a Module

Credit: Phil Tomson

Problem

You have a mixin module that defines some instance variables. Given a class that mixes in the module, you want to initialize the instance variables whenever an instance of the class is created.

Solution

Define an initialize method in the module, and call super in your class’s constructor. Here’s a Timeable module that tracks when objects are created and how old they are:

	module Timeable
	 attr_reader :time_created

	 def initialize
	   @time_created = Time.now
	 end

	 def age #in seconds
	   Time.now - @time_created
	 end
	end

Timeable has an instance variable time_created, and an initialize method that assigns Time.now (the current time) to the instance variable. Now let’s mix Timeable into another class that also defines an initialize method:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint