From: Leslie Viljoen Date: 2006-05-22T20:35:42+09:00 Subject: Re: rubynuby - confused by method name "inject" 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 } => 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 = [[1, 7, 3], [1, 2], [1, 5, 4, 1], [1, 8]] longest_sample = nil longest_length = data.inject(0) do |accum, sample| if accum > sample.length accum else longest_sample = 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 = data[0] data.each do |sample| longest_sample = sample if sample.length > longest_sample.length end puts "Longest sample: #{longest_sample.inspect}, length #{longest_length}"