From: mirian@... (Mirian Crzig Lennox) Date: 2001-06-10T23:26:52+09:00 Subject: [ruby-talk:16388] Re: other ways to create class instance? After thinking about the question Samantha raised (creating class instances without new), I realized that perl has a rather useful mechanism for this, which is "bless". In perl, any object (usually a hash) can be turned into an object of class X by calling bless on it. This allows the object to be hand-crafted beforehand. Of course, in perl the structure of objects are exposed to such a low-level that working with them is much clumsier than in a pure OO language like Ruby. But you can still do something remarkably similar: module HashAttrs def HashAttrs.construct clazz, hash clazz.new.set_attrs_from_hash hash end def set_attrs_from_hash hash hash.each { |key, value| setter = key.to_s + "=" send setter, value } self end end Then, any object that you wish to be constructible in this way need only include the HashAttrs module and declare its attr accessors, e.g. class MyClass include HashAttrs attr_accessor :foo, :bar, :baz public :foo, :bar, :baz private :foo=, :bar=, :baz= end And then you can easily instantiate an object of that class by constructing a hash mapping attrs to values, and passing that to HashAttrs.construct along with the class name: my_object_attrs = { "foo", 32, "bar", 54, "baz", 102 } my_object = HashAttrs.construct MyClass, my_object_attrs You can also combine this with the marshalling technique I described previously, so that objects can be stored/loaded easily as mere key,value pairs, and hashes acts as intermediaries between that format and the fully-instantiated object form -- with all of the code to do this in one place only, and abstracted away from the implementation of the specific classes themselves. --Mirian