From: ts Date: 2001-06-10T23:51:52+09:00 Subject: [ruby-talk:16389] Re: other ways to create class instance? >>>>> "M" == Mirian Crzig Lennox writes: M> After thinking about the question Samantha raised (creating class M> instances without new), I realized that perl has a rather useful M> mechanism for this, which is "bless". "bless" just associate a STASH with a variable M> In perl, any object (usually a hash) can be turned into an object of ^^^^^^^^^^ any variable M> class X by calling bless on it. [...] M> module HashAttrs M> def HashAttrs.construct clazz, hash M> clazz.new.set_attrs_from_hash hash M> end M> def set_attrs_from_hash hash M> hash.each { M> |key, value| M> setter = key.to_s + "=" M> send setter, value M> } M> self M> end M> end [...] M> class MyClass M> include HashAttrs M> attr_accessor :foo, :bar, :baz M> public :foo, :bar, :baz M> private :foo=, :bar=, :baz= M> end [...] M> my_object_attrs = { "foo", 32, "bar", 54, "baz", 102 } M> my_object = HashAttrs.construct MyClass, my_object_attrs Just write class A attr_accessor :foo, :bar, :baz def initialize(hash) hash.each do |k, v| eval "self.#{k}= #{v}" end end end a = A.new "foo" => 12, "bar" => 24 Guy Decoux