Ruby - Modules 2020
bogotobogo.com site search:
Modules
Modules are a way of grouping together methods, classes, and constants. Modules give us two major benefits:
- Modules provide a namespace and prevent name clashes.
- Modules implement the mixin facility.
In this article, we'll learn how to use modules.
#!/usr/bin/ruby # human.rb module Human attr_accessor :name, :height, :weight def run puts self.name + " runs" end end
Another module:
#!/usr/bin/ruby # smart.rb module Smart def act_smart return "E = mc^2" end end
We we want to write regular Ruby file which needs the modules we created:
#!/usr/bin/ruby # req.rb # How to Modules require_relative "human" require_relative "smart" module Animal def make_sound puts "Urrrr..." end end class Dog include Animal end mong = Dog.new mong.make_sound class Scientist include Human #prepend Smart # prepend supposed to work v.2.1 but it's not. include Smart def act_smart return "Scientist: E=mc**2" end end ein = Scientist.new ein.name = "Albert Einstein" puts ein.name ein.run puts ein.name + " says " + ein.act_smart
Output:
$ ./req.rb Urrrr... Albert Einstein Albert Einstein runs Albert Einstein says Scientist: E=mc**2
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization