Mixing in Modules

Modules group methods, and then you can use their functionality in different classes. To do that, the module’s code is mixed-in to other types, as in Ruby or Dart. You do this with the keyword include. When a class does an include ModuleName, its objects can use the methods of the included module as their own methods! You saw an example in Organizing Code in Classes and Modules.

Here’s another example: Both classes DVD and BlueRay include the module Debug, so objects made of these classes can use its method who_am_i?

 class​ Basic
 def​ ​initialize​(@name : String)
 end
 
 def​ ​to_s
  @name
 end
 end
 
 module​ ​Debug
 def​ ​who_am_i?
 "​​#{​self.​class​.​name​​}​​ (​​#​​#{​self.​object_id​​}​​): ​​#{​self.​to_s​​}​​"
 end
 end
 
 class​ DVD < Basic
 include​ Debug
 # ...
 end
 
 class​ BlueRay < Basic
 include​ Debug
 # ...
 end
 
 dv = DVD.​new​(​"West End Blues"​)
 br = BlueRay.​new​(​"Attack of the Martians"​)
 dv.​who_am_i?​ ​# => DVD (#40886016): West End Blues
 br.​who_am_i?​ ​# => BlueRay (#40885984): Attack of the Martians

See the use of # here? This is for when you need a literal # sign in the output.

To use the module’s methods on the class itself, you have to extend the module:

 module​ ​DebugC
 def​ ​who_am_i?
 "​​#{​self.​class​.​name​​}​​: ​​#{​self.​to_s​​}​​"
 end
 end
 
 class​ CD < Basic
 extend​ DebugC
 # ...
 end
 
 cd = CD.​new​(​"Bach's Cello Suites"​)
 cd.​who_am_i?​ ​# => Error: undefined method 'who_am_i?' for CD
 CD.​who_am_i?​ ​# => "Class: CD"

Modules can also contain abstract methods. Each class that includes them has to make its specific implementation for these methods. You’ll see examples of this in the section Applying Built-In Modules.

A class can include (and/or extend) many modules, thus importing various types of behavior, so this mechanism is a kind of multiple inheritance. But wait—doesn’t that make this a recipe for name collisions?

No. The next section shows you why it isn’t.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.47.166