Modularity organizes software functionality into separate, reusable modules. In Ruby, modules bundle methods and constants, then add those behaviors to classes or individual objects rather than creating instances themselves. section 4.0
The practical benefit appears when one general behavior applies to several classes. A class can include a module and gain its methods without duplicating their implementations. section 4.1.2
Modularity in Ruby supports several related design goals:
- Encapsulate behavior in a named module. section 4.0
- Extend classes by mixing in shared functionality. section 4.1.2
- Organize names with module-based namespaces. section 4.0
Making a class stacklike
A Stack class can include Stacklike and expose add_to_stack, take_from_stack, and stack. Running the resulting object adds three items, removes the last one, and leaves the earlier two. A nonmodular Stack implementation produces the same behavior, but the module makes stacklikeness reusable for other cases. section 4.1.2
Listing 4.2 Mixing the Stacklike module into the Stack class
require_relative "stacklike" 1
class Stack
include Stacklike 2
end
Ruby mixes a module into a class with include, allowing Stack to acquire Stacklike behavior. section 4.1.2









