From: Robert Klemme Date: 2006-05-22T22:48:03+09:00 Subject: Re: rubynuby - confused by method name "inject" 2006/5/22, Daniel N : > This is a question that I have often wondered about and I think this thread > has gone a fair way to explaining it. > > Just to make sure, I want to step through a call to inject (The sum example) > to see that I have it. Any comments would be great. > > [1,2,3].inject(0) { |cur_sum, elem| cur_sum + elem } > > Iteration 1 > cur_sum = 0, elem = 1 > cur_sum = cur_sum + elem #=> cur_sum = 0 + 1 (Replace cur_sum with the > results of the block => 1 ) > > Iteration 2 > cur_sum = 1, elem = 2 > cur_sum = cur_sum + elem #=> cur_sum = 1 + 2 (Replace cur_sum with the > results of the block => 3 ) > > Iteration 3 > cur_sum = 3, elem = 3 > cur_sum = cur_sum + elem #=> cur_sum = 3 + 3 (Replace cur_sum with the > results of the block => 6 ) > > Return cur_sum #=> 6 > > I think that part so far is ok. I get this part. but how would I step > through this? Exactly the same - only values are different. > klass = fully_qualified_name.split('::').inject(Module) { |_module, > _symbol| > _module.const_get(_symbol) > } > > instance = klass.new >> class Foo;class Bar;class Baz; end end end => nil >> "Foo::Bar::Baz".split(/::/).inject(Object) {|cl,n| print "-> ", cl, ", ", n, "\n"; cl.const_get(n)}.new -> Object, Foo -> Foo, Bar -> Foo::Bar, Baz => # Kind regards robert