4. What is a Module?
• A Module is a collection of methods and
constants.
• Similar to a regular Class but without the
concept of instantiation
• Used as a standalone entity, it can help with
namespacing
Tuesday, August 13, 13
6. So..What is a Mixin?
• A Mixin is a Module
• A SPECIAL type of
Module
Tuesday, August 13, 13
7. Special How?
• A Mixin happens when you include a
Module within a Class
• Instance Methods come to life!
• Allows a sense of multiple inheritance
• 2 objects marry and the result is greater
than the sum of the parts
Tuesday, August 13, 13
8. So, as I was saying, Enumerable
is a Module Mixin
• Provides Collection type classes with
traversal, searching, and sorting functionality
Tuesday, August 13, 13
9. Examples in Standard
Ruby Library
• Some of your BFFs include Enumerable
• Array, Hash, Set
• Range, File
Tuesday, August 13, 13
10. Some Cool Enumerable
Methods
• all? (do all items return true for the block)
• any? (do any items return true for the block)
• collect (make new collection with results)
• count
• detect (return the first item that returns
true for the block)
• find
• first
• grep (return all items that === a pattern)
• inject (iterates through the collection with
an accumulator)
• reject (returns all items that return false
for the block)
• select (returns all items that return true
for the block)
Tuesday, August 13, 13
11. Methods that must be defined if a class
includes Enumerable
• each (basically some flavor of yielding to a block for each
element in your object)
• If the class wishes to use the max, min, or
sort functions provided by Enumerable
• The “each” items of the collection must
implement <=>
• Combined comparison operator. Returns 0 if first operand equals
second, 1 if first operand is greater than the second and -1 if first
operand is less than the second.
Tuesday, August 13, 13
16. Each to her Own
• http://ruby-doc.org/core-2.0/
Enumerable.html
• http://www.ruby-doc.org/docs/
ProgrammingRuby/html/tut_modules.html
Tuesday, August 13, 13