Ruby's inject() lets you do amazing things very expressively. I first
got into inject() when realized how easy it makes getting a class by its
fully qualified name:
klass = fully_qualified_name.split('::').inject(Module) { |_module,
_symbol|
_module.const_get(_symbol)
}
instance = klass.new
In this example name "inject" totally corresponds to what it is doing
here. To me at least.
Sincerely,
Gennady.
> -----Original Message-----
> From: Robert Klemme [mailto:shortcutter / googlemail.com]
> Sent: Sunday, May 21, 2006 8:59 AM
> To: ruby-talk ML
> Subject: Re: rubynuby - confused by method name "inject"
>
> 2006/5/21, ReggW <me / yourhome.com>:
> > Jeff Pritchard wrote:
> > > Can anybody explain to me how the Enumberable#inject method is
> > > "injecting" something into something? I find it very
> difficult remember
> > > method names when I don't "get" them. So far in Ruby,
> "inject" takes
> > > the cake for least understandable method name (with my
> own particular
> > > convoluted gray matter).
> >
> > I agree!!!!
> >
> >
> > I have it marked in my "Ruby notes", as "Don't use".
> > I do this so that when I come across it again, I won't spend 2 hours
> > trying to make sense out of it's purpose.
>
> Granted that it may take some time to understand it and to recognize
> its power (took me a while, too), but - once you grokked it you'll be
> amazed how much you can do with it. A lot - if not all - methods in
> Enumerable can be elegantly implemented with inject. Try it out!
> Also, when searching the archives you'll find quite a few postings
> that show how something can be done with inject and often it's more
> elegant than other methods. Just compare the example that has been
> shown in this thread with the version using each:
>
> sum = 0
> enum.each {|x| sum += x}
> sum
>
> enum.inject(0) {|sum, x| sum + x}
>
> Kind regards
>
> robert
>
>
> --
> Have a look: http://www.flickr.com/photos/fussel-foto/
>
>