Rubynuby - confused by method name "inject"

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).

Can somebody give some examples of its use and state in words how it is
"injecting" something into something?

thanks,
jp

P.S.
If anybody wants to take a stab at "collect", that would be welcome
also.

···

--
Posted via http://www.ruby-forum.com/.

Would you prefer foldl? :-p

Well one possible explanation is that it's injecting the contents of the array and the result of the last call to the block back into the block, sort of an auto-transfusion.

The canonical inject example is the sum of the elements of an array:
irb(main):001:0> [1, 7, 2].inject(0) { |sum_so_far, current_item| sum_so_far + current_item }
=> 10

As far as collect goes, you're collecting the results of the block applied to each element in the enumerable. (I personally prefer map to collect as far as terminology goes).

irb(main):002:0> [1, 7, 2].collect { |item| item * 2 }
=> [2, 14, 4]

···

On May 20, 2006, at 10:42 PM, 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).

Can somebody give some examples of its use and state in words how it is
"injecting" something into something?

thanks,
jp

P.S.
If anybody wants to take a stab at "collect", that would be welcome
also.

--
Posted via http://www.ruby-forum.com/\.

Hi --

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).

Can somebody give some examples of its use and state in words how it is
"injecting" something into something?

thanks,
jp

P.S.
If anybody wants to take a stab at "collect", that would be welcome
also.

I have just about the mental energy for collect right now, so I'll
give that a try :slight_smile:

The basic usage (just to have an example):

You have an array: [1,2,3,4,5]
You call: new_array = array.collect {|element| element * 10 }
The result (new_array) is: [10,20,30,40,50]

Now, in terms of the word "collect" itself:

Imagine that the elements of the first array are sitting on a bus.
The conductor comes through the bus and *collects* the fare from each
element. The fare is: yourself times 10. The cumulative result is a
new array, consisting of the old array's elements but each multiplied
by 10.

So collect is an iterative process, where a new value is "collected"
from each old value, courtesy of being passed to the code block. The
new array is thus a one-to-one mapping of the old array, with the
values transformed. (So collect is also called "map" :slight_smile:

David

···

On Sun, 21 May 2006, Jeff Pritchard wrote:

--
David A. Black (dblack@wobblini.net)
* Ruby Power and Light, LLC (http://www.rubypowerandlight.com)
   > Ruby and Rails consultancy and training
* Author of "Ruby for Rails" from Manning Publications!
   > Ruby for Rails

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).

Can somebody give some examples of its use and state in words how it is
"injecting" something into something?

["foo", "bar"].inject(5) {|total, word| total + word.length } #=> 11

This example injects the result of the block applied to each element of
the collection into a single value.

I actually prefer the Haskell term, "fold" -- it repeatedly folds the
function of the value and an element of the collection back into the value.

If anybody wants to take a stab at "collect", that would be welcome
also.

I use "map", which is an alias of "collect".

ys = xs.map {|x| x * x }

It takes a block (a mapping from X to Y) and applies it to a collection
of Xs to map them to Ys.

Cheers,
Dave

I think the name originally came from Smalltalk.

···

On 5/20/06, Jeff Pritchard <jp@jeffpritchard.com> 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).

Can somebody give some examples of its use and state in words how it is
"injecting" something into something?

thanks,
jp

P.S.
If anybody wants to take a stab at "collect", that would be welcome
also.

--
Posted via http://www.ruby-forum.com/\.

[1,2,3,4,5].inject(0){|sum,num|sum+num} => 15
Which is ((((0+1)+2)+3)+4)+5

j`ey
http://www.eachmapinject.com

···

On 5/21/06, Jeff Pritchard <jp@jeffpritchard.com> 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).

Can somebody give some examples of its use and state in words how it is
"injecting" something into something?

thanks,
jp

P.S.
If anybody wants to take a stab at "collect", that would be welcome
also.

--
Posted via http://www.ruby-forum.com/\.

Jeff Pritchard wrote:

If anybody wants to take a stab at "collect", that would be welcome

I think #collect is fairly intuitive:

   addresses = contacts.collect{|contact| contact.address}

Here we collect the addresses of the contacts.

Daniel

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.

···

--
Posted via http://www.ruby-forum.com/\.

Since this old discussion is one of the top ranking pages when you
Google 'ruby inject' or 'inject method', it's probably worth adding that
since version 1.8.7 Ruby has had the #reduce method, which is an alias
of #inject.

It seems a lot of people prefer #reduce, because it's reducing the list
down to a single value. Personally I think it's just as bad. Another
commenter said, the classic example of #inject is to sum the elements of
an array. So now we have a method called 'reduce' to add elements
together?! One might expect #reduce to work more like #drop or #take or
#select--to create a smaller (reduced) subset. To me it communicates
nothing of the combining nature of the method--unless maybe I think of
it in cooking terms, where one boils a sauce to condense it, but that's
being generous I think.

It's hard to come up with a good short name for such a versatile
function without implying an increase or decrease of successive results.
I think of the word 'cumulative' when I think of how #inject is using
the result of one iteration in the next one, and 'cumulate' is a verb,
but perhaps not a very common one, and it does kind of imply an increase
in successive results. 'Accumulate' is similar.

I wouldn't mind Jeff's suggestion of 'combine', except I think it could
very easily be confused with concatenation methods like #concat and #+,
which combines two arrays into one.

But then we have 'fold', which is the name Wikipedia went with in
categorising these types of functions. Why on earth couldn't Ruby have
gone with this? Like 'reduce', it's used by a stack of other languages,
but unlike 'reduce' it doesn't imply a decrease in value. Check out the
top definitions of the word 'fold' from my dictionary:

fold
verb [ with obj. ]
1 bend (something flexible and relatively flat) over on itself so that
one part of it covers another: Sam folded up the map.
• (fold something in/into) mix an ingredient gently with (another
ingredient), especially by lifting a mixture with a spoon so as to
enclose it without stirring or beating: fold the egg whites into the
chocolate mixture.

So there's that cooking metaphor again. But how elegant is that! No
metaphor is going to be a perfect fit for all that #inject is able to
do, but I reckon #fold would be a thousand times better than #inject and
#reduce.

I'm hoping they'll add #fold as an alias method one day. But until then,
I guess I'll stick with #inject.

···

--
Posted via http://www.ruby-forum.com/.

Wooosh! (The sound of Stu's comment flying over my head.) I'll have to
take your word for it mate! :slight_smile:

···

--
Posted via http://www.ruby-forum.com/.

I agree, "map" makes a lot more sense than "collect". I'm going to just
forget about collect and consider it "personally deprecated due to poor
naming".

As for Inject, nobody has come up with a wording that makes any sense to
me yet. Does Inject have any aliases/synonyms?

thanks,
jp

P.S.
If I were to choose a synonym for the "inject" method, I might come up
with "collect". vis. "iterate over these items and collect the results
in one answer." It seems to me that this method does the same thing
that the big Latin "E" symbol (Epsilon) does in Mathematics. Is there a
name for that symbol within the math community? (I mean - besides
Epsilon). Calculus and Physics are "twenty some odd years ago" for me.

P.P.S.
Is it considered bad form to create your own aliases for things like
this? For instance, if I were to create an alias for Enumerated#inject
like "gather", and use that all over my programs, would this be
considered bad form, or just hunky-dory use of the language?

···

--
Posted via http://www.ruby-forum.com/.

Following David's suggestion, I think I'll go ahead and use it, but
always precede it with a comment so I can remember what it does when I
come back to it later. Something like:

# this "inject" method is "combining" the results from the block
operation into a single answer
[1,2,3,4,5].inject(0){|sum,num|sum+num}

This topic makes me wonder, and perhaps one of the old-timers here can
answer this. If I understand it correctly, Matz basically "invented"
ruby. Matz is, as far as I know, Japanese. Was Ruby first written with
Japanese class and method names and later translated to English? Or did
it start out in English?

thanks,
jp

ReggW wrote:

···

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.

--
Posted via http://www.ruby-forum.com/\.

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

···

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.

--
Have a look: Robert K. | Flickr

Something about "map" + "fold" is pleasantly humorous.

Fold is actually an older than functional programming concept for recursive
computation which is just more syntax to the symbolic nature of these
languages. The inverse methods unfold/misfold would be the actual removal,
deletions or cause for infection. Consider Stanford university's gene
folding distributed computing research project: http://folding.stanford.edu/

Many programmers come from different languages and have different
preferences to which /tokens/ yield the best value for their current
project. I enjoy using unix style commands like grep and so forth. Someone
who has a background in either haskall, ocamal erlang or what not may want
to use fold over reduce or use map or create their own datamapper and
declare their own name for it.

I use fold in my personal scripts. It's really not that difficult to create
your own. As far as having it in future release of the language the real
question is what would the inverse be misfold or unfold ... or leave the
user to create their own.

Drop the cooking metaphor. It's a biological concept. Consider reading Alan
Kay for your meta and linguistic concepts.

···

On Fri, Jan 3, 2014 at 9:11 AM, Kal Starkis <lists@ruby-forum.com> wrote:

Since this old discussion is one of the top ranking pages when you
Google 'ruby inject' or 'inject method', it's probably worth adding that
since version 1.8.7 Ruby has had the #reduce method, which is an alias
of #inject.

It seems a lot of people prefer #reduce, because it's reducing the list
down to a single value. Personally I think it's just as bad. Another
commenter said, the classic example of #inject is to sum the elements of
an array. So now we have a method called 'reduce' to add elements
together?! One might expect #reduce to work more like #drop or #take or
#select--to create a smaller (reduced) subset. To me it communicates
nothing of the combining nature of the method--unless maybe I think of
it in cooking terms, where one boils a sauce to condense it, but that's
being generous I think.

It's hard to come up with a good short name for such a versatile
function without implying an increase or decrease of successive results.
I think of the word 'cumulative' when I think of how #inject is using
the result of one iteration in the next one, and 'cumulate' is a verb,
but perhaps not a very common one, and it does kind of imply an increase
in successive results. 'Accumulate' is similar.

I wouldn't mind Jeff's suggestion of 'combine', except I think it could
very easily be confused with concatenation methods like #concat and #+,
which combines two arrays into one.

But then we have 'fold', which is the name Wikipedia went with in
categorising these types of functions. Why on earth couldn't Ruby have
gone with this? Like 'reduce', it's used by a stack of other languages,
but unlike 'reduce' it doesn't imply a decrease in value. Check out the
top definitions of the word 'fold' from my dictionary:

fold
verb [ with obj. ]
1 bend (something flexible and relatively flat) over on itself so that
one part of it covers another: Sam folded up the map.
• (fold something in/into) mix an ingredient gently with (another
ingredient), especially by lifting a mixture with a spoon so as to
enclose it without stirring or beating: fold the egg whites into the
chocolate mixture.

So there's that cooking metaphor again. But how elegant is that! No
metaphor is going to be a perfect fit for all that #inject is able to
do, but I reckon #fold would be a thousand times better than #inject and
#reduce.

I'm hoping they'll add #fold as an alias method one day. But until then,
I guess I'll stick with #inject.

--
Posted via http://www.ruby-forum.com/\.

I find #reduce much better than #inject, but #fold is my preference as
well. Consistent with other languages, and I've always found the "folding
an ingredient into dough" metaphor apt.

But I can live with #reduce.

···

On Fri, Jan 3, 2014 at 10:11 AM, Kal Starkis <lists@ruby-forum.com> wrote:

Since this old discussion is one of the top ranking pages when you
Google 'ruby inject' or 'inject method', it's probably worth adding that
since version 1.8.7 Ruby has had the #reduce method, which is an alias
of #inject.

It seems a lot of people prefer #reduce, because it's reducing the list
down to a single value. Personally I think it's just as bad. Another
commenter said, the classic example of #inject is to sum the elements of
an array. So now we have a method called 'reduce' to add elements
together?! One might expect #reduce to work more like #drop or #take or
#select--to create a smaller (reduced) subset. To me it communicates
nothing of the combining nature of the method--unless maybe I think of
it in cooking terms, where one boils a sauce to condense it, but that's
being generous I think.

It's hard to come up with a good short name for such a versatile
function without implying an increase or decrease of successive results.
I think of the word 'cumulative' when I think of how #inject is using
the result of one iteration in the next one, and 'cumulate' is a verb,
but perhaps not a very common one, and it does kind of imply an increase
in successive results. 'Accumulate' is similar.

I wouldn't mind Jeff's suggestion of 'combine', except I think it could
very easily be confused with concatenation methods like #concat and #+,
which combines two arrays into one.

But then we have 'fold', which is the name Wikipedia went with in
categorising these types of functions. Why on earth couldn't Ruby have
gone with this? Like 'reduce', it's used by a stack of other languages,
but unlike 'reduce' it doesn't imply a decrease in value. Check out the
top definitions of the word 'fold' from my dictionary:

fold
verb [ with obj. ]
1 bend (something flexible and relatively flat) over on itself so that
one part of it covers another: Sam folded up the map.
• (fold something in/into) mix an ingredient gently with (another
ingredient), especially by lifting a mixture with a spoon so as to
enclose it without stirring or beating: fold the egg whites into the
chocolate mixture.

So there's that cooking metaphor again. But how elegant is that! No
metaphor is going to be a perfect fit for all that #inject is able to
do, but I reckon #fold would be a thousand times better than #inject and
#reduce.

I'm hoping they'll add #fold as an alias method one day. But until then,
I guess I'll stick with #inject.

--
Posted via http://www.ruby-forum.com/\.

This statement amuses me, because Alan Kay was specifically inspired by
biological concepts (cells) when he came up with his conception of OO :slight_smile:

···

On Fri, Jan 3, 2014 at 11:45 AM, Stu <stu@rubyprogrammer.net> wrote:

Drop the cooking metaphor. It's a biological concept. Consider reading
Alan Kay for your meta and linguistic concepts.

@Avdi

=) Yup. It's a great concept. Smalltalk was built on another AI language
which uses cells which in turn branch in form of linked lists with a atomic
dereference value and a pointer to the next cell in the tree. OO messaging
is totally based on the concept where objects communicate with signals and
messages over a network. The concept of a self described system wasn't
exactly a new concept but definitely brought to a new level of control
moving into graphical systems.

@Kal
I didn't refer to it being different. I mentioned that the alias to the
"sameness" of the functions will be applicable to current programmers which
are writing code. Hence a SQL programmer might like /select/ a UNIX
programmer would use /grep/ a haskall programmer would feel comfortable
with /fold/ where a scheme programmer would use /reduce/. An erlang
programmer would embed their own MapReduce filter which would have a slick
side effect providing the removal of the jvm virus inside an ad hoc parser
on a zero width atomic contexts which would recursively reduce all ruby
code through an EvalApply self.reference reducer modulo whitespace into a
try-retry cycled core routine emitting a prolog based truth maintenance
system implemented minikanren system built with nothing more than regular
expressions!

It's a programmable programming language! Know thy computational models and
metaphors yet keep all aliases and subroutines intact and in core as to
respect all programmers with different backgrounds!

Stu wrote in post #1132133:

I use fold in my personal scripts. It's really not that difficult to
create
your own. As far as having it in future release of the language the real
question is what would the inverse be misfold or unfold ... or leave the
user to create their own.

Drop the cooking metaphor. It's a biological concept.

Hey, if the protein folding metaphor works for you, great! Strike up
another reason why 'fold' is a better name than 'inject'!

You lost me though when you started talking about 'fold' and 'reduce' as
two different things. No one here is arguing for a new method. The
thread is about the native #inject method in Ruby, and how that name
doesn't help one intuitively understand or remember what it does.

···

--
Posted via http://www.ruby-forum.com/\.

Andrew Vit wrote in post #1132140:

Something about "map" + "fold" is pleasantly humorous.

Now that you point that out, indeed it is! There you go, another fine
reason to add #fold.

(I've always preferred #map to #collect.)

···

--
Posted via http://www.ruby-forum.com/\.