It seems that this:
class Foo
end
does not invoke Class.new in Ruby 1.6.3. Is that right? Does it in 1.7?
Should it?
I am assuming that this:
class Bar
end
should be just syntactic sugar for
Bar = Class.new unless Module.constants.include? "Bar"
Here's why I think it isn't. I'm using code like the following to
demonstrate metaclass hackery for the _Little Ruby_ book. It counts the
number of instances of any class. (Please note that I'm trying to use as
little syntax as possible, so the code is not idiomatic.)
class Class
alias_method("old_new", "new")
def instances
if @instances == nil
@instances = 0
end
@instances
end
def instances=(val)
@instances = val
end
def count_new_instance
self.instances += 1
if superclass
superclass.count_new_instance
end
end
def new(*args)
count_new_instance
old_new(*args)
end
end
That doesn't work for Class.new (or any class that redefines new). I
thought it would be cute to make it work, because it lets me round out the
discussion of what inherits from what. So I did this:
class Class
@old_class_new = method("new")
def Class.new(*args)
count_new_instance
@old_class_new.call(*args)
end
end
After this:
Class.instances #=> 0
Class.new
Class.instances #=> 1
class Bar
end
Class.instances #=> 1
--
Brian Marick, marick / testing.com
www.testing.com - Software testing services and resources
www.testingcraft.com - Where software testers exchange techniques
www.visibleworkings.com - Adequate understanding of system internals