On Thu, May 29, 2003 at 07:20:00PM +0900, Simon Strandgaard wrote:
> Thanks.. Brian you have lead me to the solution.
> 
> My problem was that 'Array.extend ArrayMisc' was located in
> a method-scope. Moving the following piece of code out into the 
> global scope, then everything works.
> 
>     #Array.extend ArrayMisc
>     class Array; include ArrayMisc; end 
> 
> AFAIK. I should be able to do an 'Array.extend' as above.
> But it does not work.  Why ?  
> What is the difference between these 2 lines ?

a = Array.new        -- a is an *instance* of Array
a.extend ArrayMisc   -- adds the methods of ArrayMisc into a's singleton
                        class (i.e. they become instance methods of 'a')

class Array
  include ArrayMisc  -- adds the methods of ArrayMisc as instance methods
                        of the class Array
end

Now, class Array *does* have a singleton class, but it's not what you want
to add your method into. The singleton class of a Class is where the 'class
methods' go:

  module Foo
    def foo
      puts "hello"
    end
  end
  Array.extend Foo    # puts methods of Foo into *singleton class* of Array

  Array.foo
  #>> "hello"

In other words, you have created a method which belongs to class Array, not
which belongs to instances of class Array.

Hope this makes sense... there are several pages about this on the wiki,
including http://www.rubygarden.org/ruby?SingletonTutorial

Regards,

Brian.