You'd like to delegate some of an object's method calls to a different object, or make one object capable of " impersonating" another.
If you want to completely impersonate another object, or
delegate most of one object's calls to another, use the
delegate library. It generates custom
classes whose instances can impersonate objects of any other class.
These custom classes respond to all methods of the class they shadow, but they don't do any
work of their own apart from calling the same method on some instance
of the "real" class.
Here's some code that uses
delegate to generate
CardinalNumber, a class that acts almost
defines the same methods as
does, and it takes a genuine
as an argument to its constructor. It stores this object as a member,
and when you call any of
methods on a
it delegates that method call to the stored
Fixnum. The only major exception is the
to_s method, which I've decided to
require 'delegate' # An integer represented as an ordinal number (1st, 2nd, 3rd…), as # opposed to an ordinal number (1, 2, 3…) Generated by the # DelegateClass to have all the methods of the Fixnum class. class OrdinalNumber < DelegateClass(Fixnum) def to_s delegate_s = __getobj_ _.to_s check = abs if to_check == 11 or to_check == 12 suffix = "th" else case check % 10 when 1 then suffix = "st" when 2 then suffix = "nd" else suffix = "th" ...