Hello --

On Wed, 10 Apr 2002, Markus Jais wrote:

> hello
>
> in several libraries I found this:
> class << self
>
> now I played with it and generated the following sample
> code (does not do anything useful, just for playing with the concept)
>
> class Vector
>    def initialize (x, y)
>           @x = x
>           @y = y
>    end
>
>    class << self
>           def func
>                  puts "in func"
>           end
>    end
>
>    def my_method
>           self.func()  # Error!! why does this not work ???
>    end
>
> end
>
> v  = Vector.new(2, 4)
> Vector.func   # works
> v.my_method   # Error

You've added the instance method #func to the singleton class of which
Vector is an instance.  The instances of Vector are one level down.
You haven't added any #func method to *their* class (which is Vector).
You've only added it to their class's class.

If you change this:

  def my_method
    self.func()
  end

to this:

  def my_method
    type.func()
  end

then the search for #func will begin among the instance methods defined
in the class of which Vector is an instance, and it will be found.


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav