RichardOnRails wrote in post #994287:
Brian: Thanks for
- addressing my key issue about how to make “self” be my array, so to
speak. Question, would that redefinition of <=> contaminate uses of
“sort” in other top-level classes?
No. I only redefined <=> within the class MyElement, so it only affects
what happens when you call <=> on an object of class MyElement.
When you call sort on an Array (that is, your outer array which includes
the pairs), internally it does a quicksort. The quicksort calls a.<=>(b)
for various pairs of elements a and b within the array.
So what matters is that the elements within the array implement <=>
for comparing themselves against any other element.
- using “delegation”, which I’ve seen in those textbooks but not yet
Basically it means passing through method calls to the underlying
object. You can do this explicitly for each method of interest:
@a = a
@a[index] = val
This gives you an opportunity to customise the behaviour in any way you
like, or have one method call combine the results from invoking multiple
underlying objects, or whatever you like.
If you find it tedious to repeat lots of method definitions, then you
can look at method_missing, or delegate.rb in the Ruby standard library.
There are examples in the source code. In this case:
class MyElement < DelegateClass(Array)
self <=> other
This creates a new class which passes all unknown methods to the
a = MyElement.new([:x, :y])
You have called the ‘’ method on your object of class MyElement, and
it’s automatically passed through to the ‘’ method on the underlying