From: Jean-Hugues ROBERT Date: 2002-05-04T23:12:33+09:00 Subject: Re: dynamically assigning instance variables At 20:35 04/05/2002 +0900, David Alan Black wrote: >Hello -- > >On Sat, 4 May 2002, Jean-Hugues ROBERT wrote: > > > Question: What the preferred idiom for creating objects in Ruby ? > > The C++ idioms ('new' & overloading) seems rather unpractical to me, due > > to the inability to overload new (or any other method, for that matter) > > based on the parameters. > >I'm not sure what you mean. Isn't new() the usual way to create >objects? > > >David Let me clarify. The way you create objects using MyClass.new() is similar to the way you do it in C++. With one major limitation: There can be only one initialize() method. Whereas in C++ you can have multiple ones. The difference being what type/number of parameters each one gets (in C++ the "initialize()" method is not called "initialize()", it is called after the name of the class). So, in C++, based on what parameters you create a new object, you define multiple "constructors". The way to do it in Ruby is not natural/direct. Because you have only one initialize() method, you need to determine yourself what the caller intention was, based on the supplied parameters. def initialize( param = nil ) case param when nil # no parameter constructor ... when self.class # Copy constructor when xxx # Whatever other constructor end Some other languages will create objects based on prototypes: def initialize() proto = @@proto proto.instance_variables.each do | var | instance_eval( "#{var} = #{proto.instance_eval( #{var})}") end end Some other languages will have no "constructor" or "initialize()" specific, language defined, construct: def MyClass.create() obj = Object.new() obj.class = MyClass # Not ruby: Smalltalk's style .becomes() missing obj.body = { :@myVar1 => "Hello", :@myVar2 => "world" } # Not ruby end Some other languages just create objects, without having the method that create objects beeing named in any specific way: def MyClass.createFromInt( ii ) obj = MyClass.new() obj.foo = ii return obj end def doubleIt() obj = MyClass.new() obj.foo = self.foo * 2 end .. an so on .. The basic OO equation is: an_object is a_id + a_value + a_behaviour. There are many idioms to create objects. Appararently the Ruby one is to use SomeClass.new( some_param) that leads to: A) the creation of the object ii with no initial value and the behaviour of its class, followed by B) a call to ii.initialize( some_param). Hope this is clearer. Yours, Jean-Hugues ------------------------------------------------------------------------- Web: http://hdl.handle.net/1030.37/1.1 Phone: +33 (0) 4 92 27 74 17