Joel VanderWerf
11/8/2007 6:00:00 AM
Phrogz wrote:
> class Foo
> ALL = []
> def initialize
> ALL << self
> end
> end
>
> There's even some interesting benefits to the scoping, like:
>
> # By inheriting the superclass's initialize,
> # Bar1 instances get put into Foo::ALL
> class Bar1 < Foo; end
>
> # But I can totally branch on my own without worrying about
> # any class variable sort of nonsense
> class Bar2 < Foo
> ALL = [] # separate from Foo::ALL
> def initialize
> ALL << self
> end
> end
>
> Thanks for that, Ara!
>
Careful though, constant scoping is not dynamic:
class Foo
def self.show_all
p ALL
end
end
3.times {Foo.new}
Foo.show_all # [#<Foo:0x2ae5e8c>, #<Foo:0x2ae5e78>, #<Foo:0x2ae5e64>]
3.times {Bar2.new}
Bar2.show_all # [#<Foo:0x2ae5e8c>, #<Foo:0x2ae5e78>, #<Foo:0x2ae5e64>]
Of course, you can get dynamic scoping, it's just easy to forget:
class Foo
def self.show_all
p self::ALL
end
end
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407