From: Paul Brannan Date: 2002-03-15T23:08:45+09:00 Subject: Re: language addition: automatic 'new' On Fri, Mar 15, 2002 at 06:43:07PM +0900, Vardhan Varma wrote: > > I wrote my first >1K ruby program over the week, > and it occured to me, it would be great if > Klass(param) > be converted to > Klass.new(param) > Automagically ... > or may be Klass.__default_ctor(param), where __default_ctor defaults to > new, > and can be ressigned if required ... I'm not sure if this is a good idea, but it sounded like a challenge, so here goes: module New_Shortcuts def self.undefined_method(obj, name) raise NameError, "undefined method `#{name}' for <#{obj.type}:0x#{'%x'%(obj.id)}>" end def self.recreate ObjectSpace.each_object(Object) do |obj| case obj when Class class_name = obj.inspect if obj.respond_to?(:new) then Object.instance_eval do define_method class_name.intern, obj.method(:new).to_proc end end end end end def self.method_missing(name, *args, &block) undefined_method(self, name) end end def self.method_missing(method_name, *args, &block) first_char = method_name.to_s[0].chr if first_char == first_char.upcase then New_Shortcuts.recreate if respond_to?(method_name, true) then return __send__(method_name, *args, &block) end end New_Shortcuts.undefined_method(self, method_name) end class Foo def initialize puts "Foo!" end end Foo() #=> prints Foo! Foo() #=> same thing again, just to show it works twice Paul