From: Kent Dahl Date: 2002-03-30T16:13:55+09:00 Subject: Re: Creating an instance of a class without calling initialize() Harry Ohlsen wrote: > > For reasons that I'll go into if someone's interested, > I'd like to be able to create an instance of an arbitrary > class, without having its initialize() method called. Please do. Curious minds have been intrigued. > Is there a way to do that in pure Ruby, or, if not, to > write a C extension that allows me to do it by interacting > with the VM somehow? The naive, "thought-it-up-in-2-shakes-of-a-lambs-tail", evil-eval way: class Class def new_without_init( *args ) self.class_eval %{ alias :old_initialize_with_args :initialize def initialize( *args );end } result = self.new( *args ) self.class_eval %{ undef :initialize alias :initialize :old_initialize_with_args } result end end # Testing it... class A def initialize( a, b, c ) print a, b, c @a = a; @b = b; @c = c end attr_reader :a, :b, :c end r1 = A.new_without_init( 1,2,3 ) p r1 #=> # r2 = A.new(1,2,3) #=> 123 p r2 #=> # HTH -- (\[ Kent Dahl ]/)_ _~_ __[ http://www.stud.ntnu.no/~kentda/ ]___/~ ))\_student_/(( \__d L b__/ NTNU - graduate engineering - 4. year ) ( \__\_�|�_/__/ ) _)Industrial economics and technological management( \____/_�_\____/ (____engineering.discipline_=_Computer::Technology___)