From: leandro moreira Date: 2011-07-23T04:03:15+09:00 Subject: Re: create object by reflection It's not working. Suppose I have the builder and RSpec and I tried to use the approach but both tests failed (String fails because it can't convert array to String, and second because wrong number of arguments (1 for 2) I'm using ruby 1.9.1(1.9.2b) class Make attr_accessor :instances def initialize @instances = {} end def build(instance,clazz,*args) if args == nil @instances[instance] = Object.const_get(clazz).new else @instances[instance] = Object.const_get(clazz).new(args) end end end And it's RSpec describe Make do before(:all) do @make = Make.new end describe "Make Instruction" do it "should keep an instance of String" do created_object = "test" @make.build "instance01", "String",["test"] @make.instances["instance01"].should == created_object end it "should keep an instance of Foo" do @make.build "instance02", "Foo",["one","two"] end end end class Foo attr_accessor :one, :two def initialize(one,two) @one = one @two = two end end And the ouput from RSpec is: 1) --- Failure/Error: @make.build "instance01", "String",["test"] TypeError: can't convert Array into String # ./lib/instructions/make.rb:11:in `initialize' # ./lib/instructions/make.rb:11:in `new' # ./lib/instructions/make.rb:11:in `build' # ./spec/make_spec.rb:11:in `block (3 levels) in ' 2) --- Failure/Error: def initialize(one,two) ArgumentError: wrong number of arguments (1 for 2) # ./spec/make_spec.rb:22:in `initialize' # ./lib/instructions/make.rb:11:in `new' # ./lib/instructions/make.rb:11:in `build' # ./spec/make_spec.rb:15:in `block (3 levels) in ' -- Posted via http://www.ruby-forum.com/.