Objects and modules
The object model is small and it is everywhere. Classes and objects come first, then inheritance, modules used as mixins and as namespaces, and the idioms that follow from duck typing. The part ends with Struct and Data, the two modules that give a class comparison and enumeration, singleton methods and class << self, and equality in a value object.
6.1
Modules and mixins
Share behavior with Ruby modules through include and extend.
Open
6.2
Classes and objects
Define a class, build objects with new, expose attributes, and understand self.
Open
6.3
Inheritance
Inherit with a parent class, call super, read ancestors, and override with care.
Open
6.4
Duck typing and core idioms
Rely on methods instead of types, print with to_s, compare with Comparable, and freeze constants.
Open
6.5
Struct and Data
Struct.new for a small mutable record, Data.define for an immutable value object, and the point where a plain hash stops being the right shape.
Open
6.6
Comparable and Enumerable in your own class
Define <=> and include Comparable for sorting and comparison, define each and include Enumerable for map, select and sum: two modules that turn a class into a collection.
Open
6.7
Modules as namespaces
A module can hold names as well as methods: constants inside it, nested modules, what :: looks up, and when a module is a namespace rather than a mixin.
Open
6.8
Singleton methods and class << self
def self.x and class << self do the same thing in different words, a single object can have its own methods, and a class method really lives on the singleton class.
Open
6.9
Equality and value objects
==, eql? and hash belong together, a Data value already has all three, and a class that defines only == collects duplicates in a set.
Open