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
$ ./class.rb
in func
../class.rb:17:in `my_method': undefined method `func' for
#<Vector:0x401dbbf8> (NameError)
from ./class.rb:24
I understand that
class << self
in this case generates a class method called "func"
but I also thought that
class << object
extends an object
(like in the pickaxe book on page 243)
why does this not work with
class << self ??
why can I not call
self.func() in the method "my_method" above ??
maybe I am just doing something wrong.
If I just want to do some helper methods for my class which I use
only internally it might be simpler to write some private methods.
is there an advante using
class << self
for generating class internal helper functions instead of just private
functions
please explain me this. it seems to be a useful and powerful
concepts but I really like to understand it completely.
markus