RichardOnRails wrote in post #994287:
> Brian: Thanks for
> 1. 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.

> 2. using "delegation", which I've seen in those textbooks but not yet
> internalized.

Basically it means passing through method calls to the underlying 
object. You can do this explicitly for each method of interest:

class MyElement
  def initialize(a)
    @a = a
  end
  def size
    @a.size
  end
  def [](index)
    @a[index]
  end
  def []=(index,val)
    @a[index] = val
  end
  ... etc
end

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:

require 'delegate'
class MyElement < DelegateClass(Array)
  def <=>(other)
    self[1] <=> other[1]
  end
end

This creates a new class which passes all unknown methods to the 
underlying object.

a = MyElement.new([:x, :y])
puts a[1]

You have called the '[]' method on your object of class MyElement, and 
it's automatically passed through to the '[]' method on the underlying 
Array object.

-- 
Posted via http://www.ruby-forum.com/.