From: nobu.nokada@... Date: 2002-03-16T00:35:46+09:00 Subject: Re: language addition: automatic 'new' Hi, At Fri, 15 Mar 2002 23:08:45 +0900, Paul Brannan 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 It's too expensive to scan all objects, and a nested class name cannot be used as a method name. Also already defined methods shoudn't be overridden. Object.constants.each do |name| obj = Object.const_get(name) if Class === obj and defined?(obj.new) and !eval("defined? #{name}()", TOPLEVEL_BINDING) Object.instance_eval do define_method name, obj.method(:new).to_proc end end end -- Nobu Nakada