This would work if you made Taggable the top-level class in your class structure, but that won’t work in every situation. Every class whose objects should be taggable could derive from Taggable. Suppose you created a class called Taggable that lets you associate tags (short strings of informative metadata) with objects. You want to create a class that derives from two or more sources, but Ruby doesn’t support multiple inheritance. # NoMethodError: undefined method `new' for Math:Module Simulating Multiple Inheritance with Mixins Problem ![]() The only thing you can’t do with a module is instantiate an object from it: Class.superclass # => Module The same methods will work exactly the same way within modules. Throughout this book we talk about using methods of Module from within classes. Module is actually the superclass of Class, so every Ruby class is also a module. We cover the use of modules as packaged functionality for existing classes in Recipes 10.1 and 10.4. The Enumerable module isn’t supposed to be used on its own: it adds functionality to a class like Array or Hash. Modules are also used to package functionality for inclusion in classes. We cover this most basic use of modules in Recipes 10.5 and 10.7. ![]() Ruby’s Math module is a good example of a namespace: it provides an overarching structure for constants like Math::PI and methods like Math::log, which would otherwise clutter up the main Kernel namespace. When a module is used as a container for objects, it’s called a namespace. Get a free trial today and find answers on the fly, or master something new and useful. Join the O'Reilly online learning platform.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |