Question 1
In the Thomas/Hunt Ruby book (is this the book that keeps getting
referred to as the "axe" book? Why?) there is an example (pg 252)
of the definition of "once" in Date. This definition uses the
singleton mechanism:
class Date
class << self
def once(*ids)
# ...
end
end
# ...
end
Why? Why isn't this written:
class Date
def once(*ids)
# ...
end
# ...
end
Question 2
Why doesn't the following do what I'd expect it to, and how does
one solve this type of problem?
module Child
@level = 0
attr :level, true
end
The only thing I can think of would be:
module Observer
def observer_init # It seems like this shouldn't be neccessary
@observers = []
end
def add_observer( o )
# ...
end
# def del, notify, each, <=>
end
I'm aware that the Observer pattern is already implemented in Ruby, and
I'm not interested in a Delegation pattern solution; I'm specifically
trying to solve the problem of needing instance variables defined and
initialized from a Module.
Question 3
My last question is regarding initialization of classes. In Java, subclass
instatiations cause the initialization of base classes:
class A { public A() { System.out.println("In A"); } }
class B { public B() { System.out.println("In B"); } }
public class test { public static void main(String[] x) { B b = new B(); } }
generates:
In A
In B
In Ruby:
class A ; def initialize ; puts "In A" ; end ; end
class B < A ; def initialize ; puts "In B" ; end ; end
b = B.new
generates:
In B
What is the rational behind this? Method overloading is fine, but in
the (special) case of initialization, I thought it was generally accepted
that initializing ancestors in order was a Good Thing. I expected
Module::new to do something like:
ancestors.each{ |class| class.initialize(*args) }
I know this code wouldn't actually work, but it illustrates my point.
Thanks!
--- SER