From: Daniel N Date: 2006-05-22T20:56:21+09:00 Subject: Re: rubynuby - confused by method name "inject" ------=_Part_170869_11443239.1148298978574 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline 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 =3D 0, elem =3D 1 cur_sum =3D cur_sum + elem #=3D> cur_sum =3D 0 + 1 (Replace cur_sum with th= e results of the block =3D> 1 ) Iteration 2 cur_sum =3D 1, elem =3D 2 cur_sum =3D cur_sum + elem #=3D> cur_sum =3D 1 + 2 (Replace cur_sum with th= e results of the block =3D> 3 ) Iteration 3 cur_sum =3D 3, elem =3D 3 cur_sum =3D cur_sum + elem #=3D> cur_sum =3D 3 + 3 (Replace cur_sum with th= e results of the block =3D> 6 ) Return cur_sum #=3D> 6 I think that part so far is ok. I get this part. but how would I step through this? klass =3D fully_qualified_name.split('::').inject(Module) { |_module, _symbol| _module.const_get(_symbol) } instance =3D klass.new On 5/22/06, Leslie Viljoen wrote: > > On 5/22/06, Leslie Viljoen wrote: > > On 5/22/06, Regg Mr wrote: > > > Leslie Viljoen wrote: > > > > On 5/21/06, Jim Weirich wrote: > > > >> Jeff Pritchard wrote: > > > >> > As for Inject, nobody has come up with a wording that makes any > sense to > > > >> > me yet. Does Inject have any aliases/synonyms? > > > >> > > > >> How I remember: Inject takes a binary operation (e.g. +) and > injects it > > > >> between each element of a list. > > > >> > > > >> [1,2,3].inject { |a,b| a+b } =3D> 1+2+3 > > > > > > > > Awesome! That really helps me! > > > > > > > > > Seems like "sum" would have been a better name. > > > > Or an alias inject_operator perhaps... > > This thread has discussed "sum" already and it's no good because you > > can use any operator. I also like "accumulate" as mentioned, but > > inject_operator is sooo clear to me. > > ..though the other uses of inject defy "inject_operator"... > > data =3D [[1, 7, 3], [1, 2], [1, 5, 4, 1], [1, 8]] > > longest_sample =3D nil > longest_length =3D data.inject(0) do |accum, sample| > if accum > sample.length > accum > else > longest_sample =3D sample > sample.length > end > end > > puts "Longest sample: #{longest_sample.inspect}, length #{longest_length}= " > > ..then again, using inject to find longest seems a bit silly... > > longest_sample =3D data[0] > data.each do |sample| > longest_sample =3D sample if sample.length > longest_sample.lengt= h > end > puts "Longest sample: #{longest_sample.inspect}, length #{longest_length}= " > > ------=_Part_170869_11443239.1148298978574--