# Inject's pathological case

**URL:** <https://www.ruby-forum.com/t/injects-pathological-case/133329>\
**Category:** Ruby\
**Created:** [March 30, 2008, 7:15am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329 "2008-03-30T07:15:32Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 7:15am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/1 "2008-03-30T07:15:32Z")

</div>

I’m not sure how I feel about inject’s pathological case. What do you  
all think should happen in the following code?

[2].inject {|a, i| puts i}

```
I might have thought that the block would never be called and the 

```

method  
would return 2.  
If the block must be called, I might expect “i” to be nil.  
What actually happens is that the block is called and “i” is the  
same  
thing as “a”. I did not expect this and I’m trying to figure out how  
this  
is either consistent or useful. Can someone clue me in to this  
behaviour?  
Thank you…

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 8:21am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/2 "2008-03-30T08:21:18Z")

</div>

Just Another Victim… wrote:

> I’m not sure how I feel about inject’s pathological case. What do you  
> all think should happen in the following code?
> 
> [2].inject {|a, i| puts i}
> 
> ```
> I might have thought that the block would never be called and the 
> 
> ```
> 
> method  
> would return 2.  
> If the block must be called, I might expect “i” to be nil.

> ```
> What actually happens is that the block is called and "i" is the 
> 
> ```
> 
> same  
> thing as “a”. I did not expect this and I’m trying to figure out how  
> this  
> is either consistent or useful. Can someone clue me in to this  
> behaviour?

I’m not seeing that:

1. Two element array:

result = [2, 3].inject do |a, i|  
puts “a:#{a}”  
puts “i:#{i}”  
puts “hello”  
puts “--------”  
end

puts “result=#{result}”  
if result.nil?  
puts ‘yes’  
end

## –output:– a:2 i:3 hello

result=  
yes

1. One element array:

result = [2].inject do |a, i|  
puts “a:#{a}”  
puts “i:#{i}”  
puts “hello”  
puts “--------”  
end

puts “result=#{result}”  
if result.nil?  
puts ‘yes’  
end

–output:–  
result=2

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 8:27am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/3 "2008-03-30T08:27:04Z")

</div>

Oh, yeah:

$ ruby -v  
ruby 1.8.2 (2004-12-25) [universal-darwin8.0]

By the way, using inject() is inefficient–not to mention confusing.  
You might as well pretend it doesn’t exist.

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 9:15am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/4 "2008-03-30T09:15:12Z")

</div>

Hi –

On Sun, 30 Mar 2008, Just Another Victim of the Ambient M. wrote:

> What actually happens is that the block is called and “i” is the same  
> thing as “a”. I did not expect this and I’m trying to figure out how this  
> is either consistent or useful. Can someone clue me in to this behaviour?  
> Thank you…

Actually the block isn’t being called:

irb(main):005:0\> [2].inject {|a, i| puts “hi” }  
=\> 2  
irb(main):006:0\> [2].inject {}  
=\> 2

The value of the whole statement is 2, or, more generally, the first  
(and only) element in the enumerable. I guess that’s all it can do  
since it doesn’t have enough elements to call the block even once.

David

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 11:55am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/5 "2008-03-30T11:55:55Z")

</div>

On Mar 30, 12:27 am, 7stud – [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Oh, yeah:
> 
> $ ruby -v  
> ruby 1.8.2 (2004-12-25) [universal-darwin8.0]
> 
> By the way, using inject() is inefficient–not to mention confusing.  
> You might as well pretend it doesn’t exist.

There is some truth to that.

def collect\_repeats\_inject list  
return if == list  
list[1..-1].inject([[list.first]]){|a,e|  
if a[-1][0] == e  
a[-1] \<\< e  
else  
a \<\< [e]  
end  
a  
}.reject{|lst| lst.size \< 2 }  
end

def collect\_repeats list  
accum = [[ list.shift] ]  
list.each{|e|  
if accum[-1][0] == e  
accum[-1] \<\< e  
else  
accum \<\< [e]  
end }  
accum.reject{|lst| lst.size \< 2 }  
end

p collect\_repeats( %w(0 1 1 2 3 3 3 3 4 5 5 6) )  
p collect\_repeats( )  
p collect\_repeats\_inject( %w(0 1 1 2 3 3 3 3 4 5 5 6) )  
p collect\_repeats\_inject( )

the\_list = %w(0 1 1 2 3 3 3 3 3 3 3 3 4 5 5 6 7 8 8 9 9 9)

t = Time.now  
9999.times{ collect\_repeats\_inject( the\_list )}  
p Time.now - t  
t = Time.now  
9999.times{ collect\_repeats( the\_list )}  
p Time.now - t

— output —  
[[“1”, “1”], [“3”, “3”, “3”, “3”], [“5”, “5”]]  
  
[[“1”, “1”], [“3”, “3”, “3”, “3”], [“5”, “5”]]  
  
2.694  
0.16

And the version without inject is shorter and  
clearer.

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 11:38am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/6 "2008-03-30T11:38:41Z")

</div>

David A. Black wrote:

> Actually the block isn’t being called:  
> I guess that’s all it can do  
> since it doesn’t have enough elements to call the block even once.

To add to that, on p.456 of pickaxe2 it says that if you don’t supply an  
argument for the inject call, then the first element in the enumerable  
becomes ‘a’, and it is not included in subsequent iteration.  
Apparently, because there are no values to iterate over, the block does  
not execute.

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 12:07pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/7 "2008-03-30T12:07:42Z")

</div>

On Mar 30, 12:27 am, 7stud – [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Oh, yeah:
> 
> $ ruby -v  
> ruby 1.8.2 (2004-12-25) [universal-darwin8.0]
> 
> By the way, using inject() is inefficient–not to mention confusing.  
> You might as well pretend it doesn’t exist.

There is some truth to that.

def collect\_repeats\_inject list  
return if == list  
list[1..-1].inject([[list.first]]){|a,e|  
if a[-1][0] == e  
a[-1] \<\< e  
else  
a \<\< [e]  
end  
a  
}.reject{|lst| lst.size \< 2 }  
end

def collect\_repeats list  
return if == list  
accum = [[ list.first] ]  
list[1..-1].each{|e|  
if accum[-1][0] == e  
accum[-1] \<\< e  
else  
accum \<\< [e]  
end }  
accum.reject{|lst| lst.size \< 2 }  
end

p collect\_repeats( %w(0 1 1 2 3 3 3 3 4 5 5 6) )  
p collect\_repeats( )  
p collect\_repeats\_inject( %w(0 1 1 2 3 3 3 3 4 5 5 6) )  
p collect\_repeats\_inject( )

the\_list = %w(0 1 1 2 3 3 3 3 3 3 3 3 4 5 5 6 7 8 8 9 9 9)

t = Time.now  
9999.times{ collect\_repeats\_inject( the\_list )}  
p Time.now - t  
t = Time.now  
9999.times{ collect\_repeats( the\_list )}  
p Time.now - t

— output —  
[[“1”, “1”], [“3”, “3”, “3”, “3”], [“5”, “5”]]  
  
[[“1”, “1”], [“3”, “3”, “3”, “3”], [“5”, “5”]]  
  
2.814  
1.923

And the version without inject seems clearer.

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 4:30pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/8 "2008-03-30T16:30:23Z")

</div>

> Understand that it’s a way to reduce/fold the elements  
> of an enumerable into a single value.

Not that this is important, but personally I never liked the name  
.inject  
Though fold(l/r) is not much better either.

A peculiar thing is that the wikipedia page gives "also known variously  
as " four different names as alternative/example.

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 4:33pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/9 "2008-03-30T16:33:58Z")

</div>

On Sun, Mar 30, 2008 at 3:34 PM, Rick DeNatale [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> Maslow’s hammer and use it in inappropriate ways, such as giving it a  
> block like in the original posting to this thread.
> 
> –  
> Rick DeNatale
> 
> My blog on Ruby  
> [http://talklikeaduck.denhaven2.com/](http://talklikeaduck.denhaven2.com/)

Completely agree with Rick and furthermore you will not be able to  
understand Ruby code written by others if you do not have a basic  
understanding of inject.

I found this code in Ruby1.9 though

```
   if result.size > 0 and result.inject(false) {|k,s| s or k}

```

that kind of code explains why inject has a bad reputation.

Cheers  
Robert

–

> **[Smalltalking about Ruby](http://ruby-smalltalk.blogspot.com/)**

* * *

Whereof one cannot speak, thereof one must be silent.  
Ludwig Wittgenstein

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 5:17pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/10 "2008-03-30T17:17:48Z")

</div>

On Sun, Mar 30, 2008 at 10:30 AM, Marc H. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> > Understand that it’s a way to reduce/fold the elements  
> > of an enumerable into a single value.
> 
> Not that this is important, but personally I never liked the name  
> .inject  
> Though fold(l/r) is not much better either.
> 
> A peculiar thing is that the wikipedia page gives "also known variously  
> as " four different names as alternative/example.

It’s because the same thing has surfaced in several languages using  
different terms, and those languages have in turn influenced others.

AFAIK, Matz correct me if I’m wrong, Ruby got the name inject from  
Smalltalk, along with collect, select, detect and several other  
methods. The other three I mention have alias, map for collect,  
find\_all for select, and find for detect, but inject is still just  
inject in Ruby.

–  
Rick DeNatale

My blog on Ruby  
[http://talklikeaduck.denhaven2.com/](http://talklikeaduck.denhaven2.com/)

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 5:28pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/11 "2008-03-30T17:28:23Z")

</div>

Hi –

On Mon, 31 Mar 2008, Rick DeNatale wrote:

> It’s because the same thing has surfaced in several languages using  
> different terms, and those languages have in turn influenced others.
> 
> AFAIK, Matz correct me if I’m wrong, Ruby got the name inject from  
> Smalltalk, along with collect, select, detect and several other  
> methods. The other three I mention have alias, map for collect,  
> find\_all for select, and find for detect, but inject is still just  
> inject in Ruby.

It picks up the synonym “reduce” in 1.9 – which I think is kind of  
too bad, since inject in Ruby has such a distinctive personality and  
cult following 🙂

David

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 5:52pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/12 "2008-03-30T17:52:35Z")

</div>

On Mar 30, 2008, at 1:27 AM, 7stud – wrote:

> By the way, using inject() is inefficient–not to mention confusing.  
> You might as well pretend it doesn’t exist.

I strongly disagree with that statement.

So 7stud, you learned Python and Ruby, decided you prefer Python, and  
now hang out on the Ruby T. mailing list bad mouthing our language?  
What’s the point, if you don’t mind my asking?

James Edward G. II

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 3:34pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/13 "2008-03-30T15:34:51Z")

</div>

On 3/30/08, 7stud – [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> By the way, using inject() is inefficient–not to mention confusing.  
> You might as well pretend it doesn’t exist.

Or much better, understand that it’s a way to reduce/fold the elements  
of an enumerable into a single value.

> **[Fold (higher-order function)](https://en.wikipedia.org/wiki/Fold_%28higher-order_function%29)**
>
> In functional programming, a fold is a higher-order function that analyzes a recursive data structure and, through use of a given combining operation, recombines the results of recursively processing its constituent parts, building up a return value. Fold is also termed as reduce, accumulate, aggregate, compress, or inject. Typically, a fold is presented with a combining function, a top node of a data structure, and possibly some default values to be used under certain conditions. The fold then p...

Enumerable#inject is very useful, as long as you don’t treat it as  
Maslow’s hammer and use it in inappropriate ways, such as giving it a  
block like in the original posting to this thread.

–  
Rick DeNatale

My blog on Ruby  
[http://talklikeaduck.denhaven2.com/](http://talklikeaduck.denhaven2.com/)

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 10:05pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/14 "2008-03-30T22:05:41Z")

</div>

“David A. Black” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote in message  
news:removed\_email\_address@domain.invalid…

> > 
> 
> Actually the block isn’t being called:
> 
> irb(main):005:0\> [2].inject {|a, i| puts “hi” }  
> =\> 2  
> irb(main):006:0\> [2].inject {}  
> =\> 2
> 
> The value of the whole statement is 2, or, more generally, the first  
> (and only) element in the enumerable. I guess that’s all it can do  
> since it doesn’t have enough elements to call the block even once.

```
D'oh!
I was confused by IRB's interface, for no good reason. I'll put the

```

crack pipe down, now. It’s doing exactly what I thought it should do…

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 8:40pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/15 "2008-03-30T20:40:58Z")

</div>

On 30.03.2008 16:32, Robert D. wrote:

> I found this code in Ruby1.9 though
> 
> ```
> if result.size > 0 and result.inject(false) {|k,s| s or k}
> 
> ```
> 
> that kind of code explains why inject has a bad reputation.

That is quite a convoluted way to say

result.any?

Kind regards

robert

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 31, 2008, 3:07am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/16 "2008-03-31T03:07:35Z")

</div>

They indispensible. Once you understand the other iterators, inject  
becomes natural.

Try doing some form of aggregation without using inject. Haha fun.

# example program to illustrate inject

num\_ary = [10,37,27,398,273,28]

# summing without inject:

without\_inject\_sum = 0  
num\_ary.each{|num| without\_inject\_sum += num}

# summing with inject

with\_inject\_sum = num\_ary.inject{|sum, num| sum + num}

Julian

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 30, 2008, 11:43pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/17 "2008-03-30T23:43:27Z")

</div>

On Sun, Mar 30, 2008 at 8:27 AM, 7stud – [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> Oh, yeah:
> 
> $ ruby -v  
> ruby 1.8.2 (2004-12-25) [universal-darwin8.0]
> 
> By the way, using inject() is inefficient–not to mention confusing.  
> You might as well pretend it doesn’t exist.

I absolutely can’t agree with that. map and inject are two beautiful  
functions which should be known for the average Ruby programmer imo.  
Instead of using some loops, you can easily use map to apply a  
function on each member. I like them.

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 31, 2008, 8:29am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/18 "2008-03-31T08:29:26Z")

</div>

Hi,

In message “Re: inject’s pathological case…”  
on Mon, 31 Mar 2008 00:27:58 +0900, “David A. Black”  
[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) writes:

|\> AFAIK, Matz correct me if I’m wrong, Ruby got the name inject from  
|\> Smalltalk, along with collect, select, detect and several other  
|\> methods. The other three I mention have alias, map for collect,  
|\> find\_all for select, and find for detect, but inject is still just  
|\> inject in Ruby.  
|  
|It picks up the synonym “reduce” in 1.9 – which I think is kind of  
|too bad, since inject in Ruby has such a distinctive personality and  
|cult following 🙂

reduce, fold, foldl; these are some of the candidates. But I think I  
have to wait for consensus for a while.

```
          matz.

```

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [March 31, 2008, 5:49am UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/19 "2008-03-31T05:49:36Z")

</div>

…or you could do it like this:

def collect\_repeats\_inject(list)  
return list unless list.respond\_to?(:inject)  
collected\_hash = list.inject({}) do |collected\_repeats, item|  
( collected\_hash[item] ||= [] ) \<\< item  
collected\_hash  
end  
collected\_hash.values  
end

---

<div class="post-metadata">

**Author:** ![maz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@maz](https://www.ruby-forum.com/u/maz)\
**Post date:** [April 1, 2008, 10:13pm UTC](https://www.ruby-forum.com/t/injects-pathological-case/133329/20 "2008-04-01T22:13:52Z")

</div>

On Sun, 30 Mar 2008 15:21:20 +0900, 7stud – wrote:

> 1. One element array:  
> […]

How do you print the value for “a” and “i”?

thufir@arrakis:~/ruby$  
thufir@arrakis:~/ruby$ ruby inject\_one\_element.rb  
result=2  
thufir@arrakis:~/ruby$  
thufir@arrakis:~/ruby$ cat inject\_one\_element.rb  
result = [2].inject do |a, i|  
puts “a:#{a}”  
puts “i:#{i}”  
puts “hello”  
puts “--------”  
end

puts “result=#{result}”  
if result.nil?  
puts ‘yes’  
end  
thufir@arrakis:~/ruby$

thanks,

Thufir

[Next page](https://www.ruby-forum.com/t/injects-pathological-case/133329.md?page=2)
