130 likes | 268 Views
Ruby Modules: An Introduction. Joshua Jennings. Modules. Similar to classes Cannot have instances Cannot have sub classes. Format. module ModuleName … … … … end. Why use Modules?. Superior organization Provides a namespace Alternative to multiple inheritance. Basic Example.
E N D
Ruby Modules: An Introduction Joshua Jennings
Modules Similar to classes Cannot have instances Cannot have sub classes
Format module ModuleName … … … … end
Why use Modules? Superior organization Provides a namespace Alternative to multiple inheritance
Basic Example module CellPhone def Call puts "This device called someone." end defVoiceMail puts "This device sent voicemail." end end
Basic Example Continued require 'singleton' require 'CellPhone.rb‘ class Smartphone include Singleton include CellPhone def Info puts "This device is a smartphone." end end
Multiple Inheritance When classes can have multiple parent classes Ruby does not support this However, with modules, there is an alternative
The Answer: Mixins While multiple inheritance is not supported, a Ruby class can include the attributes of multiple modules. The functionality of the modules are “mixed in” to the Ruby class.
Basic Example Modified module PC defPlayGames puts "This device ran a video game." end def Keyboard puts "This device has a keyboard." end end
Basic Example Modified require 'singleton' require 'CellPhone.rb' require 'PC.rb' class Smartphone include Singleton include CellPhone include PC def Info puts "This device is a smartphone." end end Smartphone.instance.PlayGames Smartphone.instance.Keyboard Smartphone.instance.Call Smartphone.instance.VoiceMail Smartphone.instance.Info